關gzip壓縮,我有新發現
1 gzip的壓縮效果是立竿見影的:
2 網站是否開啟gzip的查看方式
2.1 打開Chrome瀏覽器,按 F12打開調試面板
2.2 切換到network頁簽,在網路請求列表的表頭,滑鼠右鍵==>Response Headers==>Content Encoding
這一欄如果顯示gzip,證明啟用了gzip壓縮。
3. gzip壓縮方案
3.1 方案一 前端打包構建時進行gzip壓縮
3.1.1 安裝插件compression-webpack-plugin
yarn add -D [email protected]
3.1.2 在webpack中配置compression-webpack-plugin
const CompressionPlugin = require('compression-webpack-plugin'); module.exports = { plugins: [ new CompressionPlugin({ algorithm: 'gzip', // 使用gzip壓縮 test: /\.js$|\.html$|\.css$/, // 匹配文件名 filename: '[path].gz[query]', // 壓縮後的文件名(保持原文件名,後綴加.gz) minRatio: 0.8, // 壓縮率小於0.8才會壓縮 threshold: 10240, // 對超過10k的數據壓縮 deleteOriginalAssets: false, // 是否刪除未壓縮的源文件 }), ], }, };
3.1.3 在Nginx中配置載入靜態的本地gz文件
nginx 靜態壓縮需要使用 ngx_http_gzip_static_module 模組,nginx_http_gzip_static_module 模組允許發送擴展名為 .gz 的預壓縮文件,而不是常規文件。默認情況下未構建此模組,應使用 –with-http_gzip_static_module 配置參數啟用它 。重新編譯nginx,添加參數–with-http_gzip_static_module
./configure --with-http_gzip_static_module
然後修改 nginx.conf 配置文件:
http { include mime.types; default_type application/octet-stream; #提高伺服器讀寫文件性能 sendfile on; #tcp_nopush on; keepalive_timeout 65; # 開啟gzip gzip_static on; server { listen 8462; server_name localhost; location / { root dist; index index.html index.htm; } error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } } }
3.2 方案二 伺服器在線gzip壓縮
http { include mime.types; default_type application/octet-stream; #提高伺服器讀寫文件性能 sendfile on; #tcp_nopush on; #keepalive_timeout 0; keepalive_timeout 65; # 開啟gzip gzip on; #壓縮級別官網建議是6 數字越大壓縮的越好,也越佔用CPU時間 #1.隨著壓縮級別的升高,壓縮比有所提高,但到了級別6後,很難再提高; #2.隨著壓縮級別的升高,處理時間明顯變慢; #3.gzip很消耗cpu的性能,高並發情況下cpu達到100% gzip_comp_level 6; # 壓縮的類型 html,css,xml,js,php # 二進位資源:例如圖片/mp3這樣的二進位文件,不必壓縮;因為壓縮率比較小, 比如100->80位元組,而且壓縮也是耗費CPU資源的. # text/javascript是IE6,7,8才能識別的js標籤 gzip_types text/plain text/css application/xml application/javascript text/javascript application/x-httpd-php; #nginx用作反向代理時啟用 #off – 關閉所有的代理結果數據壓縮 #expired – 如果header中包含」Expires」頭資訊,啟用壓縮 #no-cache – 如果header中包含」Cache-Control:no-cache」頭資訊,啟用壓縮 #no-store – 如果header中包含」Cache-Control:no-store」頭資訊,啟用壓縮 #private – 如果header中包含」Cache-Control:private」頭資訊,啟用壓縮 #no_last_modified – 啟用壓縮,如果header中包含」Last_Modified」頭資訊,啟用壓縮 #no_etag – 啟用壓縮,如果header中包含「ETag」頭資訊,啟用壓縮 #auth – 啟用壓縮,如果header中包含「Authorization」頭資訊,啟用壓縮 #any – 無條件壓縮所有結果數據 gzip_proxied off # 是否在http header中添加Vary: Accept-Encoding,建議開啟 gzip_vary on # 設置用於處理請求壓縮的緩衝區數量和大小 gzip_buffers 4 16k; # 大於多少位元組進行壓縮,以K為單位,當值為0時,所有頁面都進行壓縮 gzip_min_length 10 # 開始壓縮的http協議版本(可以不設置,目前幾乎全是1.1協議) gzip_http_version 1.1; # 配置禁用gzip條件,可以不設置,目前幾乎沒有IE6,支援正則。此處表示ie6及以下不啟用gzip(因為ie低版本不支援) gzip_disable "MSIE [1-6]\."; server { listen 8462; server_name localhost; location / { root dist; index index.html index.htm; } error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } } }
4.兩種方案的優缺點:
1.在前端進行gzip壓縮,不耗伺服器性能,但需要重新編譯nginx,添加gzip_static模組。
2.使用nginx實時進行gzip壓縮,缺點就是耗性能,對於前端而言的優點是什麼都不用管,因為有時候前端不一定有nginx的配置修改許可權。
參考文章:
[3] Nginx性能優化功能- Gzip壓縮(大幅度提高頁面載入速度)