温馨提示×

LNMP环境如何开启Gzip

小樊
36
2026-08-06 02:13:06
栏目: 编程语言

LNMP 环境(Linux + Nginx + MySQL + PHP) 中,开启 Gzip 压缩 主要是在 Nginx 中配置。下面给你一份通用、安全、生产可用的配置说明。


一、确认 Nginx 支持 Gzip

Nginx 默认已内置 ngx_http_gzip_module,一般无需额外安装。

检查:

nginx -V 2>&1 | grep gzip

只要能看到 http_gzip_module 即可。


二、开启 Gzip(推荐配置)

编辑 Nginx 配置文件(常见路径):

vim /etc/nginx/nginx.conf

或在站点配置中:

vim /etc/nginx/conf.d/your_site.conf

✅ 推荐配置(放在 http {}server {} 中)

http {
    gzip on;
    gzip_min_length 1k;
    gzip_buffers 4 16k;
    gzip_http_version 1.1;
    gzip_comp_level 5;
    gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript image/svg+xml;
    gzip_vary on;
    gzip_disable "MSIE [1-6]\.";
}

三、参数说明(重要)

参数 说明
gzip on 开启 Gzip
gzip_min_length 小于该大小不压缩(避免浪费 CPU)
gzip_comp_level 压缩级别(1–9,5 是性能与压缩率平衡点)
gzip_types 需要压缩的 MIME 类型
gzip_vary 让代理服务器识别是否启用压缩
gzip_disable 禁用旧 IE 浏览器

注意
不要压缩图片(jpg/png/gif),已经压缩过,反而浪费 CPU。


四、PHP 输出是否需要 Gzip?

不需要
Nginx 的 Gzip 会自动压缩 PHP 输出的内容(如 text/html)。

只要:

gzip_types 包含 text/html

不需要 在 PHP 中再开启 zlib.output_compression


五、重载 Nginx 配置

nginx -t
systemctl reload nginx

六、验证是否生效

方法 1:浏览器开发者工具

  • Network → 任意 JS/CSS → Response Headers
  • 看到:
Content-Encoding: gzip

方法 2:curl 验证

curl -H "Accept-Encoding: gzip" -I http://yourdomain.com/style.css

返回:

Content-Encoding: gzip

七、常见问题

❌ Gzip 没生效?

检查:

  1. 是否在 location ~ \.php$ {} 里被覆盖
  2. 是否响应内容太小(< gzip_min_length
  3. 是否命中缓存(刷新或禁用缓存)

八、LNMP 一键包用户注意

如果你用的是 LNMP 一键安装包

  • 配置文件通常在:
/usr/local/nginx/conf/nginx.conf
  • 虚拟主机:
/usr/local/nginx/conf/vhost/yourdomain.conf

如果你愿意,可以把你的 Nginx 站点配置贴出来,我可以帮你精确调整 Gzip 配置,避免踩坑。

0