Nginx(四):压缩功能详解

时间:2021-03-09 20:36:00

gzip (GNU-ZIP) 是一种压缩技术。经过 gzip 压缩后页面大小可以变为原来的 30%甚至更小。 这样,用户浏览页面的时候速度会快得多。  gzip 的压缩页面需要浏览器和服务器双方都支持,实 际上就是服务器端压缩,传到浏览器后浏览器解压并解析。浏览器那里不需要我们担心,因为 IE、 Firefox 、Opera 、Chrome 等绝大多数浏览器都支持解析 gzip 过的页面。

压缩好处:将响应报⽂发送⾄客户端之前可以启⽤压缩功能,这能够有效地节约带宽,并提⾼响应⾄客户端的速度,压缩会消耗nginx的cpu性能。

一、开启gzip

gzip压缩可以配置在http,server和location模块下,Nginx 的压缩输出由一组 gzip 压缩指令来实现。

Vim打开Nginx配置文件

vim /usr/local/nginx/conf/nginx.conf
gzip on;                                 //开启gzip压缩
gzip_min_length 1k; //不压缩临界值,大于1K的才压缩,一般不用改
gzip_buffers 16k; //压缩缓存,也不用改
gzip_http_version 1.1; //压缩协议版本,用了反向代理的话,末端通信是HTTP/1.0,默认是HTTP/1.1
gzip_comp_leve1 ; //压缩级别,1-10,数字越大压缩的越好,时间也越长
gzip_types text/p1ain app1ication/x-javascript text/css app1ication/xml; //进行压缩的文件类型,缺啥补啥就行,JavaScript有两种写法,最好都写上吧,总有人抱怨js文件没有压缩,其实多写一种格式就行了
gzip_vary on; //跟Squid等缓存服务有关,on的话会在Header里增加"Vary: Accept-Encoding"
gzip_disable "MSIE [1-6]\."; //IE6对Gzip不怎么友好,不给它Gzip了

二、:wq保存退出,重新加载Nginx

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

三、用curl测试Gzip是否成功开启

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

HTTP/1.1  OK
Server: nginx/1.0.
Date: Sun, Aug :: GMT
Content-Type: text/html; charset=UTF-
Connection: keep-alive
X-Powered-By: PHP/5.2.17p1
X-Pingback: http://www.slyar.com/blog/xmlrpc.php
Content-Encoding: gzip

页面成功压缩

curl -I -H "Accept-Encoding: gzip, deflate" "http://www.slyar.com/blog/wp-content/plugins/photonic/include/css/photonic.css"

HTTP/1.1  OK
Server: nginx/1.0.
Date: Sun, Aug :: GMT
Content-Type: text/css
Last-Modified: Sun, Aug :: GMT
Connection: keep-alive
Expires: Mon, Aug :: GMT
Cache-Control: max-age=
Content-Encoding: gzip

css文件成功压缩

curl -I -H "Accept-Encoding: gzip, deflate" "http://www.slyar.com/blog/wp-includes/js/jquery/jquery.js"

HTTP/1.1  OK
Server: nginx/1.0.
Date: Sun, Aug :: GMT
Content-Type: application/x-javascript
Last-Modified: Thu, Jul :: GMT
Connection: keep-alive
Expires: Mon, Aug :: GMT
Cache-Control: max-age=
Content-Encoding: gzip

js文件成功压缩

curl -I -H "Accept-Encoding: gzip, deflate" "http://www.slyar.com/blog/wp-content/uploads/2012/08/2012-08-23_203542.png"

HTTP/1.1  OK
Server: nginx/1.0.
Date: Sun, Aug :: GMT
Content-Type: image/png
Last-Modified: Thu, Aug :: GMT
Connection: keep-alive
Expires: Tue, Sep :: GMT
Cache-Control: max-age=
Content-Encoding: gzip

图片成功压缩

curl -I -H "Accept-Encoding: gzip, deflate" "http://www.slyar.com/blog/wp-content/plugins/wp-multicollinks/wp-multicollinks.css"

HTTP/1.1  OK
Server: nginx/1.0.
Date: Sun, Aug :: GMT
Content-Type: text/css
Content-Length:
Last-Modified: Sat, May :: GMT
Connection: keep-alive
Expires: Mon, Aug :: GMT
Cache-Control: max-age=
Accept-Ranges: bytes

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