首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

清除網頁緩存的跨語言對照表:HTML / ASP / PHP / JSP

     編輯:PHP 相關知識

無論前端靜態頁或後端動態語言,禁用瀏覽器緩存的核心都是發送正確的 HTTP 標頭或 Meta 標籤。本文整理四大主流技術棧的標準寫法,可直接複製部署。

HTML 靜態頁(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。

ASP (Classic ASP / VBScript)

<%
Response.Expires = -1
Response.ExpiresAbsolute = Now() - 1
Response.CacheControl = "no-cache"
%>

PHP

<?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");
?>

JSP / Servlet

<%
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
%>

Spring MVC / Controller 統一攔截(建議)

@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);
    }
}

快速驗證方法

  1. 開啟瀏覽器開發者工具 → Network → 選取文件 → Headers。
  2. 確認 Cache-Control: no-store, no-cache, must-revalidate、Pragma: no-cache、Expires: -1 或過去日期。
  3. 按 F5 重整,確認 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;
}

原則:動態頁/隱私資料/交易流程 → 禁用緩存;靜態資源/公開圖片/字體 → 積極緩存。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved