為啥使用gzip壓縮
開啟nginx的gzip壓縮,網(wǎng)頁中的JS,css等靜態(tài)資源的大小會(huì)大大的減少從而節(jié)約大量的帶寬,提高傳輸效率,給用戶快的體驗(yàn)。
nginx實(shí)現(xiàn)gzip
nginx實(shí)現(xiàn)資源壓縮的原理是通過默認(rèn)集成的ngx_http_gzip_module模塊攔截請(qǐng)求,并對(duì)需要做gzip的類型做gzip,使用非常簡單直接開啟,設(shè)置選項(xiàng)即可。。
gzip生效后的請(qǐng)求頭和響應(yīng)頭
request?headers: accept-encoding:gzip,deflate,sdch response?headers: content-encoding:gzip cache-control:max-age240
gzip的處理過程
從http協(xié)議的角度看,請(qǐng)求頭聲明acceopt-encoding:gzip deflate sdch(是指壓縮算法,其中sdch是google自己家推的一種壓縮方式)
服務(wù)器-〉回應(yīng)-〉把內(nèi)容用gzip壓縮-〉發(fā)送給瀏覽器-》瀏覽器解碼gzip->接收gzip壓縮內(nèi)容
gzip的常用配置參數(shù)
-
gzip on|off??是否開啟gzip
-
gzip_buffers??4k??緩沖(壓縮在內(nèi)存中緩沖幾塊?每塊多大?)
-
gzip_comp_level [1-9] ??推薦6??壓縮級(jí)別,級(jí)別越高壓縮的最小,同時(shí)越浪費(fèi)cpu資源
-
gzip_disable ??正則匹配ua是什么樣的uri不進(jìn)行g(shù)zip
-
gzip_min_length??200開始?jí)嚎s的最小長度,小于這個(gè)長度nginx不對(duì)其進(jìn)行壓縮
-
gzip_http_version??1.0|1.1開始?jí)嚎s的http協(xié)議版本(默認(rèn)1.1)
-
gzip_proxied??設(shè)置請(qǐng)求者代理服務(wù)器,該如何緩存內(nèi)容
-
gzip_types? text/plain??application/xml??對(duì)哪些類型的文件用壓縮如txt,xml,html,css
-
gzip_vary??off?是否傳輸gzip壓縮標(biāo)志
nginx配置gzip
靜態(tài)頁面index.html
nbsp;html> ??<meta> ??<title>演示nginx做gzip壓縮</title> ??<script></script> @@##@@ <h1>nginx實(shí)現(xiàn)gzip壓縮,減少帶寬的占用,同時(shí)提升網(wǎng)站速度</h1> <h1>nginx實(shí)現(xiàn)gzip壓縮,減少帶寬的占用,同時(shí)提升網(wǎng)站速度</h1> <h1>nginx實(shí)現(xiàn)gzip壓縮,減少帶寬的占用,同時(shí)提升網(wǎng)站速度</h1> <h1>nginx實(shí)現(xiàn)gzip壓縮,減少帶寬的占用,同時(shí)提升網(wǎng)站速度</h1> <h1>nginx實(shí)現(xiàn)gzip壓縮,減少帶寬的占用,同時(shí)提升網(wǎng)站速度</h1> <h1>nginx實(shí)現(xiàn)gzip壓縮,減少帶寬的占用,同時(shí)提升網(wǎng)站速度</h1>
nginx的配置
server{ ????listen?80; ????server_name?localhost?192.168.0.96; ????gzip?on; ????gzip_buffers?32?4k; ????gzip_comp_level?6; ????gzip_min_length?200; ????gzip_types?application/javascript?application/x-javascript?text/javascript?text/xml?text/css; ????gzip_vary?off; ????root?/users/lidong/desktop/wwwroot/test; ????index?index.php?index.html?index.htm; ????access_log?/users/lidong/wwwlogs/access.log; ????error_log?/users/lidong/wwwlogs/error.log; ????location?~?[^/].php(/|$)?{ ????????fastcgi_pass??127.0.0.1:9000; ????????fastcgi_index?index.php; ????????fastcgi_param?script_filename?$document_root$fastcgi_script_name; ????????include????fastcgi_params; ????} }
為使用gzip前的頁面請(qǐng)求:
開啟了gzip頁面的請(qǐng)求:
注意
-
圖片,mp3一般不需要壓縮,因?yàn)閴嚎s率比較小
-
一般壓縮text,css,js,xml格式的文件
-
比較小的文件不需要壓縮,有可能還會(huì)比源文件更大
-
二進(jìn)制文件不需要壓縮