瀏覽器為了提高載入速度,會自動快取靜態資源(HTML、CSS、JS、圖片)。但當內容頻繁更新、涉及敏感資料或動態生成頁面時,快取會導致使用者看到舊版內容,甚至造成資安風險。因此,正確設定防快取標頭至關重要。
在 <head> 區塊加入以下 meta 標籤,指示瀏覽器不快取:
<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Expires" content="0" />
注意:Meta 標籤僅對 HTML 文件本身有效,無法控制 CSS/JS/圖片等外部資源;且部分舊版瀏覽器或 Proxy 伺服器可能忽略此設定,建議搭配伺服器端標頭使用。
<%
Response.Buffer = True
Response.ExpiresAbsolute = Now() - 1
Response.Expires = 0
Response.CacheControl = "no-cache"
Response.AddHeader "Pragma", "No-Cache"
%>
<?php
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // 過去日期
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-cache, no-store, must-revalidate, max-age=0');
header('Pragma: no-cache');
?>
放在腳本最頂端,確保在輸出任何內容前送出標頭。
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetNoStore();
Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));
response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
response.setHeader("Pragma", "no-cache");
response.setDateHeader("Expires", 0);
app.use((req, res, next) => {
res.set('Cache-Control', 'no-cache, no-store, must-revalidate');
res.set('Pragma', 'no-cache');
res.set('Expires', '0');
next();
});
對於靜態資源(CSS、JS、圖片),不建議全域關閉快取(會嚴重影響效能),改用「版本號」或「雜湊值」查詢字串:
<link rel="stylesheet" href="style.css?v=20240115" />
<script src="app.js?v=1.2.3"></script>
每次部署更新版本號,瀏覽器視為新資源而重新下載,兼顧效能與即時性。
Cache-Control: no-cache 等指令。200 OK(重新下載)而非 304 Not Modified(使用快取)。防快取策略應視專案需求分層實施:動態頁面、API、敏感資料務必啟用伺服器端標頭;靜態資源採用版本化快取破壞。正確配置能確保使用者永遠看到最新內容,同時維持最佳效能表現。