nginx开启gzip压缩 gzip提高页面加载速度

发布时间:2020-11-07编辑:脚本学堂
本文介绍了nginx中开启gzip压缩的方法,使用gzip压缩提高页面加载速度,并且gzip压缩测试实例供参考,有需要的朋友可以看看。

gzip压缩 测试环境:debian 6

1、vim打开nginx配置文件
vim /usr/local/nginx/conf/nginx.conf

2、找到如下一段,进行修改
 

复制代码 代码示例:
gzip on;
gzip_min_length 1k;
gzip_buffers 4 16k;
#gzip_http_version 1.0;
gzip_comp_level 2;
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;
gzip_disable "msie [1-6].";

3、配置节说明
第1行:开启gzip

第2行:不压缩临界值,大于1k的才压缩,一般不用改

第3行:buffer,就是,嗯,算了不解释了,不用改

第4行:用了反向代理的话,末端通信是http/1.0,有需求的应该也不用看我这科普文了;有这句的话注释了就行了,默认是http/1.1

第5行:压缩级别,1-10,数字越大压缩的越好,时间也越长,看心情随便改吧

第6行:进行压缩的文件类型,缺啥补啥就行了,javascript有两种写法,最好都写上吧,总有人抱怨js文件没有压缩,其实多写一种格式就行了

第7行:跟squid等缓存服务有关,on的话会在header里增加"vary: accept-encoding",我不需要这玩意,自己对照情况看着办吧

第8行:ie6对gzip不怎么友好,不给它gzip了

4、:wq保存退出,重新加载nginx

/usr/local/nginx/sbin/nginx -s reload

5、用curl测试gzip是否成功开启
 

复制代码 代码示例:

curl -i -h "accept-encoding: gzip, deflate" "http://www.jb200.com/blog/"

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://www.jb200.com/blog/xmlrpc.php
content-encoding: gzip

页面成功压缩
 

复制代码 代码示例:

curl -i -h "accept-encoding: gzip, deflate" "http://www.jb200.com/blog/wp-content/plugins/photonic/include/css/photonic.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=43200
content-encoding: gzip

css文件成功压缩
 

复制代码 代码示例:

curl -i -h "accept-encoding: gzip, deflate" "http://www.jb200.com/blog/wp-includes/js/jquery/jquery.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

js文件成功压缩
 

复制代码 代码示例:

curl -i -h "accept-encoding: gzip, deflate" "http://www.jb200.com/blog/wp-content/uploads/2012/08/2012-08-23_203542.png"

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

图片成功压缩
 

复制代码 代码示例:

curl -i -h "accept-encoding: gzip, deflate" "http://www.jb200.com/blog/wp-content/plugins/wp-multicollinks/wp-multicollinks.css"

http/1.1 200 ok
server: nginx/1.0.15
date: sun, 26 aug 2012 18:23:27 gmt
content-type: text/css
content-length: 180
last-modified: sat, 02 may 2009 08:46:15 gmt
connection: keep-alive
expires: mon, 27 aug 2012 06:23:27 gmt
cache-control: max-age=43200
accept-ranges: bytes

最后来个不到1k的文件,由于我的阈值是1k,所以没压缩。