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

Apache 效能優化三板斧:Expires 快取、Gzip 壓縮、關閉 ETag

編輯:關於伺服器

目標

依據 Yahoo! Best Practices 34 條規範中的 3 項伺服器層面建議,透過 mod_headers、mod_expires、mod_deflate 模組大幅降低頁面載入時間。

一、設定靜態資源長效快取 (Expires / Cache-Control)

方案 A:mod_headers (精確控制)

LoadModule headers_module modules/mod_headers.so

# 固定過期時間 (相容舊瀏覽器)

  Header set Expires "Thu, 15 Apr 2026 20:00:00 GMT"


# Cache-Control: max-age=604800 (7 天) — 現代瀏覽器優先

  Header set Cache-Control "max-age=604800, public"

方案 B:mod_expires (語意化、維護性佳)

LoadModule expires_module modules/mod_expires.so
ExpiresActive On
ExpiresDefault "access plus 1 month"
ExpiresByType image/x-icon "access plus 1 month"
ExpiresByType application/javascript "access plus 1 week"
ExpiresByType text/css "access plus 3 days"
ExpiresByType image/gif "access plus 1 month"
ExpiresByType image/png "access plus 1 month"
ExpiresByType image/jpeg "access plus 1 month"
ExpiresByType text/plain "access plus 1 week"
ExpiresByType application/x-shockwave-flash "access plus 1 month"
ExpiresByType video/x-flv "access plus 1 month"
ExpiresByType application/pdf "access plus 1 month"
ExpiresByType text/html "access plus 1 week"

建議採用方案 B,語意清晰且自動處理日期計算。

二、啟用 Gzip/Deflate 壓縮文字內容

LoadModule deflate_module modules/mod_deflate.so
LoadModule headers_module modules/mod_headers.so


  # 僅壓縮文字類 MIME,避免二進位檔二次壓縮
  AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css application/javascript application/json application/xml
  # 針對副檔名補充
  AddOutputFilter DEFLATE html xml css js json
  # 瀏覽器相容:排除已知有問題的 User-Agent (可選)
  BrowserMatch ^Mozilla/4 gzip-only-text/html
  BrowserMatch ^Mozilla/4\.0[678] no-gzip
  BrowserMatch \bMSIE !no-gzip !gzip-only-text/html

三、關閉 ETag 避免多伺服器不一致導致快取失效

FileETag None

叢集環境下,不同節點產生的 Inode/Size/Time 組合 ETag 不同,導致瀏覽器誤判需重新下載。關閉後完全依賴 Expires/Cache-Control。

驗證成效

  1. 安裝 Firefox YSlow 或 Chrome Lighthouse 掃描評分。
  2. 檢查回應標頭:Cache-Control: max-age=604800、Content-Encoding: gzip、無 ETag。
  3. 觀察二次載入 Network 面板:靜態資源應為 from disk cache / 304 Not Modified。

注意事項

  • 動態頁面 (PHP/JSP/ASP.NET) 勿設長效快取,需在應用層控制 Cache-Control: no-store, private。
  • 壓縮等級預設 6 (Z_DEFAULT_COMPRESSION),CPU/體積平衡佳;極少需調整 DeflateCompressionLevel。
  • HTTP/2 啟用後,Header 壓縮 (HPACK) 與多路複用已部分取代 Gzip 優勢,但保留 Gzip 仍有益於 HTTP/1.1 客戶端。
Copyright © Windows教程網 All Rights Reserved