开启Nginx GZIP压缩网页

技术运维Nginx 484

在每个站点/项目的conf文件中配置gzip会出现重复设置gzip的错误,提示内容:

nginx: [emerg] "gzip" directive is duplicate in /etc/nginx/sites-enabled/yoursite.com.conf

所以最好还是把gzip写在 /etc/nginx/nginx.conf文件中

    server {
        listen       80 default_server;
        listen       [::]:80 default_server;
        server_name  _;
        root         /usr/share/nginx/html;

#...........

#gzip setting

        gzip on;
        gzip_vary on;
        gzip_min_length 10240;
        gzip_proxied expired no-cache no-store private auth;
        gzip_types text/plain text/css text/xml text/javascript application/x-javascript application/xml;
        gzip_disable "MSIE [1-6]\.";

#..........

8X-------------------------以上是2018-07-02更新------------------------------------------

http{}中加入以下代码

gzip on;    #开启Gzip
gzip_min_length 1k;    #不压缩临界值,大于1K的才压缩,一般不用改
gzip_buffers 4 16k;    #buffer,不用改
#gzip_http_version 1.0;    #用了反向代理的话,末端通信是HTTP/1.0;默认是HTTP/1.1
gzip_comp_level 2;    #压缩级别,1-10,数字越大压缩的越好,时间也越长
gzip_types text/plain application/x-javascript text/css application/xml text/javascript application/x-httpd-php image/jpeg image/gif image/png;    #进行压缩的文件类型
gzip_vary off;    #跟Squid等缓存服务有关,on的话会在Header里增加"Vary: Accept-Encoding"
gzip_disable "MSIE [1-6]\.";    #IE6以下的版本对Gzip不支持,所以不为这些浏览器开启Gzip

最后测试gzip是否开启

curl -I -H "Accept-Encoding: gzip, deflate" "http://www.example.com/"

HTTP/1.1 200 OK
Server: nginx/1.12.2
Date: Thu, 04 Jan 2018 08:42:15 GMT
Content-Type: text/html;charset=utf-8
Connection: keep-alive
Set-Cookie: wire=ginhh9nf7sn9op8au854fgis37; path=/; HttpOnly
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate
Pragma: no-cache
X-Powered-By: 
X-Cache: MISS - 1515055333.716
Content-Encoding: gzip

相关链接:

Post Comment