nginx下gzip配置参数详解

2019-10-17 20:45:50王冬梅

expired – 启用压缩,如果header头中包含 “Expires” 头信息
no-cache – 启用压缩,如果header头中包含 “Cache-Control:no-cache” 头信息
no-store – 启用压缩,如果header头中包含 “Cache-Control:no-store” 头信息
private – 启用压缩,如果header头中包含 “Cache-Control:private” 头信息
no_last_modified – 启用压缩,如果header头中不包含 “Last-Modified” 头信息
no_etag – 启用压缩 ,如果header头中不包含 “ETag” 头信息
auth – 启用压缩 , 如果header头中包含 “Authorization” 头信息
any – 无条件启用压缩

gzip_types

语法: gzip_types mime-type [mime-type ...]
默认值: gzip_types text/html
作用域: http, server, location
匹配MIME类型进行压缩,(无论是否指定)”text/html”类型总是会被压缩的。
注意:如果作为http server来使用,主配置文件中要包含文件类型配置文件

http
{
include conf/mime.types;
……
}

如果你希望压缩常规的文件类型,可以写成这个样子

http
{
include conf/mime.types;

gzip on;
gzip_min_length 1000;
gzip_buffers 4 8k;
gzip_http_version 1.1;
gzip_types text/plain application/x-javascript text/css text/html application/xml;

……
}

默认情况下,Nginx的gzip压缩是关闭的
同时,Nginx默认只对text/html进行压缩
所以,开启gzip的指令如下:

gzip on;
gzip_http_version 1.0;
gzip_disable “MSIE [1-6].”;
gzip_types text/plain application/x-javascript text/css text/javascript;

关于gzip_types,如果你想让图片也开启gzip压缩,那么用以下这段吧:

gzip_types text/plain application/x-javascript text/css text/javascript application/x-httpd-php image/jpeg image/gif image/png;

注意:

1. 其中的gzip_http_version的设置,它的默认值是1.1,就是说对HTTP/1.1协议的请求才会进行gzip压缩,如果我们使用了proxy_pass进行反向代理,那么nginx和后端的upstream server之间是用HTTP/1.0协议通信的

This module makes it possible to transfer requests to another server.
It is an HTTP/1.0 proxy without the ability for keep-alive requests yet. (As a result, backend connections are created and destroyed on every request.) Nginx talks HTTP/1.1 to the browser and HTTP/1.0 to the backend server. As such it handles keep-alive to the browser.

如果我们使用nginx通过反向代理做Cache Server,而且前端的nginx没有开启gzip,同时,我们后端的nginx上没有设置gzip_http_version为1.0,那么Cache的url将不会进行gzip压缩

2. gzip_disable的设置是禁用IE6的gzip压缩,又是因为杯具的IE6
IE6的某些版本对gzip的压缩支持很不好,会造成页面的假死,今天产品的同学就测试出了这个问题,后来调试后,发现是对img进行gzip后造成IE6的假死,把对img的gzip压缩去掉后就正常了,为了确保其它的IE6版本不出问题,所以就加上了gzip_disable的设置