PageSpeed Insights、GTmetrix、Lighthouse 等工具常提示:「**未設定有效的 Cache-Control 或 Expires 標頭**」,導致瀏覽器無法快取靜態資源 (圖片、CSS、JS、字體等),每次造訪皆重複下載,拖慢頁面載入速度。
Apache 設定檔 (httpd.conf 或 apache2.conf):
LoadModule headers_module modules/mod_headers.so
sudo a2enmod headers && sudo systemctl reload apache2/etc/httpd/conf.modules.d/00-base.conf
# 圖片、字體、媒體、樣式、腳本:長期快取 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"
| 指令 | 含義 | 適用場景 |
|---|---|---|
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"
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"
public/private/immutable/must-revalidate 等精細控制# 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) |
Apache 設定快取標頭的標準作法:**啟用 mod_headers → 用 FilesMatch 分類資源 → 依靜態/動態特性設定 max-age + public/private + immutable/must-revalidate**。配合前端建構的檔名雜湊,實現「長效快取、秒級更新」的最佳體驗。記得用 <IfModule> 保護配置,避免模組缺失導致服務中斷。