無論前端靜態頁或後端動態語言,禁用瀏覽器緩存的核心都是發送正確的 HTTP 標頭或 Meta 標籤。本文整理四大主流技術棧的標準寫法,可直接複製部署。
<head>)<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Cache-Control" content="no-cache, must-revalidate">
<meta http-equiv="Expires" content="0">
<!-- 或具體過去日期 -->
<meta http-equiv="Expires" content="Wed, 26 Feb 1997 08:21:57 GMT">
⚠️ Meta 標籤**僅對瀏覽器生效**,Proxy/CDN 會忽略;動態語言請改用 HTTP Header。
<%
Response.Expires = -1
Response.ExpiresAbsolute = Now() - 1
Response.CacheControl = "no-cache"
%>
<?php
// 必須在任何輸出之前
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Cache-Control: no-cache, must-revalidate");
header("Pragma: no-cache");
// 現代加強版
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Pragma: no-cache");
header("Expires: -1");
?>
<%
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
response.setDateHeader("Expires", 1); // 1970/01/01 00:00:01 GMT
%>
@ControllerAdvice
public class NoCacheAdvice {
@ModelAttribute
public void addNoCacheHeaders(HttpServletResponse resp) {
resp.setHeader("Cache-Control", "no-store, no-cache, must-revalidate, max-age=0");
resp.setHeader("Pragma", "no-cache");
resp.setDateHeader("Expires", 0);
}
}
Cache-Control: no-store, no-cache, must-revalidate、Pragma: no-cache、Expires: -1 或過去日期。Status Code: 200 OK(而非 304 Not Modified)。Nginx 範例:
location ~* \.(jpg|jpeg|png|gif|ico|css|js|woff2?)$ {
expires 30d;
add_header Cache-Control "public, max-age=2592000";
}
location /api/private/ {
add_header Cache-Control "no-store, no-cache, must-revalidate";
add_header Pragma "no-cache";
expires -1;
}
原則:動態頁/隱私資料/交易流程 → 禁用緩存;靜態資源/公開圖片/字體 → 積極緩存。