萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 伺服器教學

Apache 啟用 mod_headers 設定 Cache-Control:解決「未設定 max-age/expires」優化靜態資源快取

問題背景

PageSpeed Insights、GTmetrix、Lighthouse 等工具常提示:「**未設定有效的 Cache-Control 或 Expires 標頭**」,導致瀏覽器無法快取靜態資源 (圖片、CSS、JS、字體等),每次造訪皆重複下載,拖慢頁面載入速度。

解決方案:啟用 mod_headers + 設定 Cache-Control

步驟 1:確認/啟用 mod_headers 模組

Apache 設定檔 (httpd.conf 或 apache2.conf):

LoadModule headers_module modules/mod_headers.so
  • Ubuntu/Debian:sudo a2enmod headers && sudo systemctl reload apache2
  • RHEL/CentOS/Fedora:通常預設已載入,檢查 /etc/httpd/conf.modules.d/00-base.conf

步驟 2:在 .htaccess 或虛擬主機配置中加入快取規則


    # 圖片、字體、媒體、樣式、腳本:長期快取 7 天 (604800 秒)
    
        Header set Cache-Control "max-age=604800, public, immutable"
    

    # XML、TXT、資料檔:中等快取 5 小時 (18000 秒),需驗證
    
        Header set Cache-Control "max-age=18000, public, must-revalidate"
    

    # HTML、PHP、動態頁面:短期快取 1 小時 (3600 秒),必須驗證
    
        Header set Cache-Control "max-age=3600, private, must-revalidate"
    

Cache-Control 指令值詳細解析

指令含義適用場景
max-age=秒數資源在快取中可重用的最長秒數所有快取資源
public允許中繼快取 (CDN、Proxy) 儲存靜態資源、公開內容
private僅瀏覽器私有快取,中繼節點不得儲存個人化頁面、認證後內容
immutable資源永不變更,瀏覽器可跳過重新驗證 (HTTP 刷新也不用)帶雜湊檔名的靜態資源 (如 app.a1b2c3.js)
must-revalidate過期後**必須**向伺服器驗證 (不可使用過期副本)動態內容、頻繁更新資源
no-cache每次使用前必須驗證 (但可快取內容)極度動態內容
no-store完全不快取敏感資料、銀行交易頁面

進階:配合檔名雜湊實現長效快取 + 即時更新

現代前端建構工具 (Webpack、Vite、Rollup) 產出帶雜湊檔名:

app.abc123.js
style.def456.css
image.ghi789.png

Apache 規則:


    # 帶雜湊的靜態資源:1 年 + immutable (最高效)
    
        Header set Cache-Control "max-age=31536000, public, immutable"
    
    
    # 不帶雜湊的靜態資源:7 天
    
        Header set Cache-Control "max-age=604800, public"
    

替代方案:mod_expires (更簡潔但功能較少)


    ExpiresActive On
    ExpiresDefault "access plus 1 month"
    ExpiresByType image/jpeg "access plus 1 year"
    ExpiresByType image/png "access plus 1 year"
    ExpiresByType text/css "access plus 1 month"
    ExpiresByType application/javascript "access plus 1 month"
    ExpiresByType font/woff2 "access plus 1 year"
  • 優點:語法簡單、按 MIME 類型設定
  • 缺點:無法設定 public/private/immutable/must-revalidate 等精細控制
  • 建議:**mod_headers 為主,mod_expires 為輔**

驗證快取標頭生效

# curl 檢查回應標頭
curl -I https://example.com/style.css

# 預期輸出包含:
HTTP/2 200
cache-control: max-age=604800, public, immutable
content-type: text/css
etag: "abc123"
last-modified: Mon, 14 Oct 2024 10:00:00 GMT
...

瀏覽器開發者工具 → Network → 點選資源 → Headers → 查看 cache-control。

常見錯誤與避坑

錯誤後果修正
未用 <IfModule mod_headers.c> 包裹模組未載入時 Apache 啟動失敗 (500 錯誤)務必包裹條件判斷
對動態頁面 (PHP) 設長期 public 快取使用者看到過時/他人資料、安全風險動態頁面用 private, must-revalidate 或 no-cache
靜態資源檔名無雜湊卻設 immutable部署新版本後瀏覽器拒絕更新僅對帶雜湊檔名設 immutable
HTTPS 網站快取標頭被中繼 Proxy 剝離CDN/防火牆移除 Cache-Control檢查 CDN 設定 (Cloudflare: Cache Level = Respect Existing Headers)

效能影響量化

  • 正確快取可減少 **50-80% 的重複請求**
  • 首次造訪 (FCP/LCP) 無影響,**重複造訪載入時間大幅縮短**
  • 頻寬成本降低、伺服器負載下降、Core Web Vitals 提升

總結

Apache 設定快取標頭的標準作法:**啟用 mod_headers → 用 FilesMatch 分類資源 → 依靜態/動態特性設定 max-age + public/private + immutable/must-revalidate**。配合前端建構的檔名雜湊,實現「長效快取、秒級更新」的最佳體驗。記得用 <IfModule> 保護配置,避免模組缺失導致服務中斷。

copyright © 萬盛學電腦網 all rights reserved