在 LNMP 环境(Linux + Nginx + MySQL + PHP) 中,开启 Gzip 压缩 主要是在 Nginx 中配置。下面给你一份通用、安全、生产可用的配置说明。
Nginx 默认已内置 ngx_http_gzip_module,一般无需额外安装。
检查:
nginx -V 2>&1 | grep gzip
只要能看到 http_gzip_module 即可。
编辑 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。
✅ 不需要
Nginx 的 Gzip 会自动压缩 PHP 输出的内容(如 text/html)。
只要:
gzip_types 包含 text/html
你 不需要 在 PHP 中再开启 zlib.output_compression。
nginx -t
systemctl reload nginx
Content-Encoding: gzip
curl -H "Accept-Encoding: gzip" -I http://yourdomain.com/style.css
返回:
Content-Encoding: gzip
检查:
location ~ \.php$ {} 里被覆盖gzip_min_length)如果你用的是 LNMP 一键安装包:
/usr/local/nginx/conf/nginx.conf
/usr/local/nginx/conf/vhost/yourdomain.conf
如果你愿意,可以把你的 Nginx 站点配置贴出来,我可以帮你精确调整 Gzip 配置,避免踩坑。