動態頁面、API 介面、使用者個人化內容等,必須確保瀏覽器不使用本地快取,每次都向伺服器請求最新資料。
<?php
// 1. 設定過期時間為過去時間
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
// 2. Last-Modified 設為當前 GMT 時間
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
// 3. HTTP/1.1 標準快取控制
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false); // 相容舊版 IE
// 4. HTTP/1.0 相容
header("Pragma: no-cache");
// 5. 針對 HTTPS/代理伺服器的額外防護
header("Vary: *");
?>
| Header | HTTP 版本 | 作用 |
|---|---|---|
| Expires | 1.0/1.1 | 指定內容過期時間,設為過去即強制過期 |
| Cache-Control | 1.1 | 核心控制指令:no-store 不儲存、no-cache 驗證後使用、must-revalidate 必須驗證 |
| Pragma | 1.0 | 舊版相容,no-cache 效果同 Cache-Control |
| Last-Modified | 1.0/1.1 | 配合 If-Modified-Since 進行條件請求 |
| Vary | 1.1 | 告知代理伺服器根據請求標頭(如 Cookie、Accept-Language)區分快取版本 |
Cache-Control: no-cache:瀏覽器仍可能儲存內容,只是使用前會驗證。需加 no-store 禁止儲存。max-age=31536000)並配合檔名雜湊版本控制。session_start() 之後設定:Session 預設會送出 Cache-Control: no-store, no-cache, must-revalidate,但建議在 session_start() 前顯式設定以確保一致性。# Nginx
location /api/ {
add_header Cache-Control "no-store, no-cache, must-revalidate, max-age=0";
add_header Pragma "no-cache";
add_header Expires "Mon, 26 Jul 1997 05:00:00 GMT";
}
# Apache (.htaccess)
<IfModule mod_headers.c>
Header set Cache-Control "no-store, no-cache, must-revalidate, max-age=0"
Header set Pragma "no-cache"
Header set Expires "Mon, 26 Jul 1997 05:00:00 GMT"
</IfModule>
快取控制是前後端協作的關鍵。動態內容務必加上完整防快取 Header;靜態資源則應積極快取並透過版本號管理更新。理解 HTTP 快取機制,能有效解決「改了程式碼瀏覽器不更新」的經典問題。