Nginx支持静态和动态两种包体gzip压缩方式,分别对应模块ngx_http_gzip_static,ngx_http_gzip。
我们知道gzip是CPU密集型的应用,实时动态压缩比较消耗CPU资源。另外,如果使用gzip,则sendfile零拷贝技术无法使用。为进一步提高Nginx的性能,我们可以使用静态gzip压缩,提前将需要压缩的文件压缩好,当客服请求到达时,直接发送压缩好的.gz文件,如此就减轻了服务器CPU的压力,提高了性能。缺省ngx_http_gzip_static模块并未启用,需要重新编译。
#注:根据需要自行添加其它参数
./configure --with-http_gzip_static_module
准备.gz文件:所有待压缩的文件,需要保留源文件和.gz文件,在相同WEB目录。如下,以index.html为例。
#压缩保留源文件的方法:
[root@test01 html]# gzip -c index.html > index.html.gz
[root@test01 html]# ll index.*
-rw-r--r--. 1 root root 620 Jun 23 2021 index.html
-rw-r--r--. 1 root root 401 Jun 23 2021 index.html.gz
使用touch同步源文件和.gz文件的修改时间。文件修改时间对应Last-Modified响应字段,HTTP缓存中使用很广泛,同步二者时间,目的是保持缓存过期判断的一致性。
touch index.html.gz -r index.html
添加配置文件:
gzip_static on;
gzip_static优先级高于gzip,$gzip_ratio对于gzip_static不生效,如果gzip_static失效,如缺少.gz,则gzip会生效。
gzip_static生效时,和gzip不同,Content-Encoding和Cotent-Length可以同时存在,因为响应在发送前已经明确其大小。
实际执行的效果:
[root@test01 html]#