Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> 電腦軟體教學 >> 伺服器技術 >> 關於伺服器

Apache 與 Nginx 啟用 Gzip 壓縮完整教學:減少 70% 傳輸流量

編輯:關於伺服器

為什麼要啟用 Gzip?

  • 頻寬節省: 文字類資源(HTML、CSS、JS、JSON、XML)壓縮率通常達 70%~90%。
  • 載入加速: 減少傳輸位元組數,特別對行動裝置、高延遲網路效果顯著。
  • 相容性極高: 現代瀏覽器(95%+)皆支援 Accept-Encoding: gzip, deflate。
  • SEO 加分: 頁面速度是 Google 排名因素之一。

Apache 啟用 mod_deflate (Gzip)

確認模組已載入:LoadModule deflate_module modules/mod_deflate.so

在 httpd.conf 或虛擬主機配置中加入:

# BEGIN GZIP
<IfModule mod_deflate.c>
    # 指定要壓縮的 MIME 類型
    AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css
    AddOutputFilterByType DEFLATE application/javascript application/json application/xml
    AddOutputFilterByType DEFLATE application/x-javascript text/javascript
    
    # 避免對已壓縮檔案(圖片、字體、影片)再次壓縮浪費 CPU
    # SetEnvIfNoCase Request_URI \.(?:gif|jpe?g|png|woff2?|mp4|pdf)$ no-gzip dont-vary
    
    # 處理代理快取問題
    <IfModule mod_headers.c>
        Header append Vary User-Agent env=!dont-vary
    </IfModule>
</IfModule>
# END GZIP

重啟 Apache:systemctl restart httpd 或 apachectl graceful。

Nginx 啟用 Gzip

在 nginx.conf 的 http、server 或 location 區塊加入:

# Gzip 基礎設定
gzip on;
gzip_vary on;                    # 傳送 Vary: Accept-Encoding 標頭
gzip_min_length 1024;            # 最小壓縮門檻 1KB,避免小檔壓縮後變大
gzip_buffers 16 8k;              # 壓縮緩衝區
gzip_http_version 1.1;           # 支援 HTTP/1.1
gzip_comp_level 6;               # 壓縮等級 1-9,6 平衡 CPU 與體積
gzip_types
    text/plain text/css text/xml
    application/javascript application/json application/xml
    application/x-javascript text/javascript
    application/vnd.ms-fontobject font/opentype;  # 字體檔亦可壓縮

# 針對舊版 IE 6 禁用 gzip(可選)
# gzip_disable "MSIE [1-6]\.";

重新載入 Nginx:nginx -s reload。

驗證壓縮是否生效

  1. 瀏覽器開發者工具: Network 標籤 → 查看 Response Headers 是否有 Content-Encoding: gzip。
  2. 命令列測試: curl -H "Accept-Encoding: gzip" -I https://example.com/style.css 檢查回應標頭。
  3. 線上工具: HTTP Compression Test、站長工具 Gzip 檢測。

進階優化建議

  • 預先壓縮: Nginx gzip_static on; 直接服務 .gz 預壓縮檔,省 CPU。
  • Brotil 替代: 現代瀏覽器支援 br 壓縮率更高,Nginx 需編譯 ngx_brotli 模組。
  • CDN 層面: 雲端 CDN(Cloudflare、Akamai、CloudFront)通常預設啟用壓縮,源站可關閉減輕負載。
Copyright © Windows教程網 All Rights Reserved