首頁  >  文章  >  運維  >  nginx中怎麼使用gzip壓縮提升網站速度

nginx中怎麼使用gzip壓縮提升網站速度

WBOY
WBOY轉載
2023-05-12 22:34:101548瀏覽

為啥使用gzip壓縮

開啟nginx的gzip壓縮,網頁中的js,css等靜態資源的大小會大大的減少從而節省大量的頻寬,提高傳輸效率,給使用者快的體驗。

nginx實作gzip

nginx實作資源壓縮的原理是透過預設整合的ngx_http_gzip_module模組攔截請求,並對需要做gzip的類型做gzip,使用非常簡單直接開啟,設定選項即可。 。

gzip生效後的請求頭和回應頭

request headers:
accept-encoding:gzip,deflate,sdch

response headers:
content-encoding:gzip
cache-control:max-age240

gzip的處理過程

從http協定的角度看,請求頭宣告acceopt- encoding:gzip deflate sdch(是指壓縮演算法,其中sdch是google自己家推的一種壓縮方式)
伺服器-〉回應-〉把內容用gzip壓縮-〉發送給瀏覽器-》瀏覽器解碼gzip ->接收gzip壓縮內容

gzip的常用設定參數

  • gzip on|off  是否開啟gzip

  • #gzip_buffers  4k  緩衝(壓縮在記憶體中緩衝幾塊?每塊多大?)

  • gzip_comp_level [1-9]   建議6  級別,等級壓縮的壓縮級別,等級壓縮的壓縮級別,等級壓縮的壓縮級別,等級。最小,同時越浪費cpu資源

  • gzip_disable   正則匹配ua是什麼樣的uri不進行gzip

  • #gzip_min_length  200開始壓縮的最小長度,小於這個長度nginx不對其進行壓縮

  • gzip_http_version  1.0|1.1開始壓縮的http協定版本(預設1.1)

  • gzip_proxied  設定請求者代理伺服器,該如何快取內容

  • gzip_types  text/plain  application/xml  對哪些類型的檔案用壓縮如txt,xml,html,css

nginx中怎麼使用gzip壓縮提升網站速度

nginx中怎麼使用gzip壓縮提升網站速度

nginx中怎麼使用gzip壓縮提升網站速度

gzip_vary  off 是否傳輸gzip壓縮標誌

  • nginx設定gzip
  • # 靜態頁面index.html

    ##nginx設定gzip
  • 靜態頁面index.html

    <!doctype html>
    <html>
    <head>
      <meta charset="utf-8">
      <title>演示nginx做gzip压缩</title>
      <script src="./jquery.js" ></script>
    </head>
    <body>
    <img  src="./nginx_img.jpeg"   style="max-width:90%" / alt="nginx中怎麼使用gzip壓縮提升網站速度" >
    <h1>nginx实现gzip压缩,减少带宽的占用,同时提升网站速度</h1>
    <h1>nginx实现gzip压缩,减少带宽的占用,同时提升网站速度</h1>
    <h1>nginx实现gzip压缩,减少带宽的占用,同时提升网站速度</h1>
    <h1>nginx实现gzip压缩,减少带宽的占用,同时提升网站速度</h1>
    <h1>nginx实现gzip压缩,减少带宽的占用,同时提升网站速度</h1>
    <h1>nginx实现gzip压缩,减少带宽的占用,同时提升网站速度</h1>
    </body>
    </html>
  • 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前的頁面請求:

######開啟了gzip頁面的請求:########## #################注意###############圖片,mp3一般不需要壓縮,因為壓縮率比較小##### ########一般壓縮text,css,js,xml格式的檔案############比比較小的檔案不需要壓縮,有可能還會比原始檔更大# ###########二進位檔案不需要壓縮##########

以上是nginx中怎麼使用gzip壓縮提升網站速度的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:yisu.com。如有侵權,請聯絡admin@php.cn刪除