原创 Nginx 开启 Gzip

在 Chrome 提供的 Lighthouse 功能上检测本站点,发现 Javascript 并没有开启 gzip,首页有开启,Ngnix 默认配置中没有开启 JS 的 gzip 压缩。

下图是检测结果,详见 启用文本压缩open in new window

1. cURL 命令检测网页是否开启 gzip

通过 curl 发送 "Accept-Encoding: gzip,deflate" Header 可以检测网页是否开启 gzip 压缩,如果返回 content-encoding: gzip,则表示支持 gzip 压缩。

$ curl -I -H "Accept-Encoding: gzip,deflate" https://dhcp.cn/
HTTP/2 200
server: istio-envoy
date: Sat, 26 Feb 2022 13:22:39 GMT
content-type: text/html
last-modified: Sun, 02 Jan 2022 03:25:44 GMT
etag: W/"61d11b38-383e"
content-encoding: gzip
x-envoy-upstream-service-time: 2
1
2
3
4
5
6
7
8
9

找到一个临时的 JS 文件检测,发现未开启 Gzip。

$ curl -I -H "Accept-Encoding: gzip,deflate" https://dhcp.cn/assets/js/8567.a0bdc1ee.js
HTTP/2 200
server: istio-envoy
date: Sat, 26 Feb 2022 13:23:23 GMT
content-type: application/javascript
content-length: 123172
last-modified: Sun, 02 Jan 2022 03:25:42 GMT
etag: "61d11b36-1e124"
accept-ranges: bytes
x-envoy-upstream-service-time: 2
1
2
3
4
5
6
7
8
9
10

2. Nginx 开启 gzip

在 nginx.conf 中新增如下配置,由于默认 gzip_types 没有 application/javascript,需要手动添加。

在 Nginx 的官方文档 Module ngx_http_gzip_moduleopen in new window 中说明了 gzip_types 的默认值为 text/html;

...
    gzip  on;
    gzip_types  text/html text/plain application/javascript application/x-javascript text/css application/xml text/javascript image/svg+xml image/jpeg image/gif image/png image/x-icon;
...
1
2
3
4

3. 检测 JavaScript gzip 开启后效果

可以看到已经返回了 content-encoding: gzip

$ curl -I -H "Accept-Encoding: gzip,deflate" https://dhcp.cn/assets/js/8567.a0bdc1ee.js
HTTP/2 200
server: istio-envoy
date: Sat, 26 Feb 2022 14:03:09 GMT
content-type: application/javascript
last-modified: Sat, 26 Feb 2022 14:00:33 GMT
etag: W/"621a3281-1e124"
content-encoding: gzip
x-envoy-upstream-service-time: 1
1
2
3
4
5
6
7
8
9

Chrome 的 lighthouse 的 Enable text compression 检查项已经通过了,网站访问速度加快了。

扩展阅读

在 Nginx 的官方文档 Module ngx_http_gzip_moduleopen in new window 介绍了 gzip 支持如下指令

gzipgzip_buffersgzip_comp_levelgzip_disablegzip_http_versiongzip_min_lengthgzip_proxiedgzip_typesgzip_vary