Nginx 四 壓縮功能詳解

2022-09-22 20:33:08 字數 3495 閱讀 7225

gzip (gnu-zip) 是一種壓縮技術。經過 gzip 壓縮後頁面大小可以變為原來的 30%甚至更小。 這樣,使用者瀏覽頁面的時候速度會快得多。  gzip 的壓縮頁面需要瀏覽器和伺服器雙方都支援,實 際上就是伺服器端壓縮,傳到瀏覽器後瀏覽器解壓並解析。瀏覽器那裡不需要我們擔心,因為 ie、 firefox 、opera 、chrome 等絕大多數瀏覽器都支援解析 gzip 過的頁面。

壓縮好處:將響應報⽂傳送⾄客戶端之前可以啟⽤壓縮功能,這能夠有效地節約頻寬,並提⾼響應⾄客戶端的速度,壓縮會消耗nginx的cpu效能。

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

416k; //壓縮快取,也不用改

gzip_http_version

1.1; //壓縮協議版本,用了反向**的話,末端通訊是http/1.0,預設是http/1.1

gzip_comp_leve1

2; //壓縮級別,1-10,數字越大壓縮的越好,時間也越長

gzip_vary on; //跟squid等快取服務有關,on的話會在header裡增加"vary: accept-encoding"

gzip_disable "msie [1-6]\."; //ie6對gzip不怎麼友好,不給它gzip了

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

curl -i -h "

accept-encoding: gzip, deflate""

"http/1.1

200ok

server: nginx/1.0.15

date: sun,

26 aug 2012

18:13:09

gmtcontent-type: text/html; charset=utf-8

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""

wp-content/plugins/photonic/include/css/photonic.css

"http/1.1

200ok

server: nginx/1.0.15

date: sun,

26 aug 2012

18:21:25

gmtcontent-type: text/css

last-modified: sun, 26 aug 2012

15:17:07

gmtconnection: keep-alive

expires: mon,

27 aug 2012

06:21:25

gmtcache-control: max-age=43200

content-encoding: gzip

css檔案成功壓縮

curl -i -h "

accept-encoding: gzip, deflate""

wp-includes/js/jquery/jquery.js

"http/1.1

200ok

server: nginx/1.0.15

date: sun,

26 aug 2012

18:21:38

gmtlast-modified: thu, 12 jul 2012

17:42:45

gmtconnection: keep-alive

expires: mon,

27 aug 2012

06:21:38

gmtcache-control: max-age=43200

content-encoding: gzip

js檔案成功壓縮

curl -i -h "

accept-encoding: gzip, deflate""

wp-content/uploads/2012/08/2012-08-23_203542.png

"http/1.1

200ok

server: nginx/1.0.15

date: sun,

26 aug 2012

18:22:45

gmtcontent-type: image/png

last-modified: thu, 23 aug 2012

13:50:53

gmtconnection: keep-alive

expires: tue,

25 sep 2012

18:22:45

gmtcache-control: max-age=2592000

content-encoding: gzip

成功壓縮

curl -i -h "

accept-encoding: gzip, deflate""

wp-content/plugins/wp-multicollinks/wp-multicollinks.css

"http/1.1

200ok

server: nginx/1.0.15

date: sun,

26 aug 2012

18:23:27

gmtcontent-type: text/css

content-length: 180

last-modified: sat, 02 may 2009

08:46:15

gmtconnection: keep-alive

expires: mon,

27 aug 2012

06:23:27

gmtcache-control: max-age=43200

accept-ranges: bytes

最後來個不到1k的檔案,由於我的閾值是1k,所以沒壓縮