实战在 nginx配置中开启gzip压缩

1、Vim打开Nginx配置文件,或者通过ftp下载到本地修改。


  1. vim /etc/nginx/nginx.conf //具体位置是你服务器nginx的安装配置

2、找到如下面这一句,进行修改,如果前面还了#说明没有开启gzip。


  1. #gzip on;

3、更改为如下内容


  1. gzip on;
  2. gzip_min_length 1k;
  3. gzip_buffers 4 16k;
  4. #gzip_http_version 1.0;
  5. gzip_comp_level 2;
  6. gzip_types text/plain application/x-javascript text/css application/xml text/javascript application/x-httpd-php image/jpeg image/gif image/png;
  7. gzip_vary off;
  8. gzip_disable "MSIE [1-6]\.";

4、保存退出,重启nginx


  1. service nginx restart

二、配置的解释


  1. gzip on;
  2. #第1行:开启Gzip
  3. gzip_min_length 1k;
  4. #第2行:不压缩临界值,大于1K的才压缩,一般不用改
  5. gzip_buffers 4 16k;
  6. #第3行:buffer,就是,嗯,算了不解释了,不用改
  7. gzip_http_version 1.0;
  8. #第4行:用了反向代理的话,末端通信是HTTP/1.0,有需求的应该也不用看我这科普文了;有这句的话注释了就行了,默认是HTTP/1.1
  9. gzip_comp_level 2;
  10. #第5行:压缩级别,1-10,数字越大压缩的越好,时间也越长,看心情随便改吧
  11. gzip_types text/plain application/x-javascript text/css application/xml text/javascript application/x-httpd-php image/jpeg image/gif image/png;
  12. #第6行:进行压缩的文件类型,缺啥补啥就行了,JavaScript有两种写法,最好都写上吧,总有人抱怨js文件没有压缩,其实多写一种格式就行了
  13. gzip_vary off;
  14. #第7行:跟Squid等缓存服务有关,on的话会在Header里增加"Vary: Accept-Encoding",我不需要这玩意,自己对照情况看着办吧
  15. gzip_disable "MSIE [1-6]\.";
  16. #第8行:IE6对Gzip不怎么友好,不给它Gzip了

三、测试一下是否成功

1、测试页面是否开启Gzip


  1. curl -I -H "Accept-Encoding: gzip, deflate" "http://www.devdo.net/"

HTTP/1.1 200 OK
Server: nginx/1.0.15
Date: Sun, 26 Aug 2012 18:13:09 GMT
Content-Type: text/html; charset=UTF-8
Connection: keep-alive
X-Powered-By: PHP/5.2.17p1
X-Pingback: http://ifxoxo.com/xmlrpc.php
Content-Encoding: gzip //页面成功压缩

2、测试css


  1. curl -I -H "Accept-Encoding: gzip, deflate" "http://www.devdo.net/wp-content/themes/frontopen2_v1.5.04.15/style.css"

HTTP/1.1 200 OK
Server: nginx/1.0.15
Date: Sun, 26 Aug 2012 18:21:25 GMT
Content-Type: text/css
Last-Modified: Sun, 26 Aug 2012 15:17:07 GMT
Connection: keep-alive
Expires: Mon, 27 Aug 2012 06:21:25 GMT
Cache-Control: max-age=3600
Content-Encoding: gzip

3、测试js文件


  1. curl -I -H "Accept-Encoding: gzip, deflate" "http://www.devdo.net/wp-content/themes/frontopen2_v1.5.04.15/js/common-scripts.js"

HTTP/1.1 200 OK
Server: nginx/1.0.15
Date: Sun, 26 Aug 2012 18:21:38 GMT
Content-Type: application/x-javascript
Last-Modified: Thu, 12 Jul 2012 17:42:45 GMT
Connection: keep-alive
Expires: Mon, 27 Aug 2012 06:21:38 GMT
Cache-Control: max-age=43200
Content-Encoding: gzip

4、测试图片


  1. curl -I -H "Accept-Encoding: gzip, deflate" "http://www.devdo.net/wp-content/uploads/2015/06/2015-06-02.jpg"

HTTP/1.1 200 OK
Server: nginx/1.0.15
Date: Sun, 26 Aug 2012 18:22:45 GMT
Content-Type: image/png
Last-Modified: Thu, 23 Aug 2012 13:50:53 GMT
Connection: keep-alive
Expires: Tue, 25 Sep 2012 18:22:45 GMT
Cache-Control: max-age=2592000
Content-Encoding: gzip

你可能感兴趣的:(nginx)