<p>Nginx强制HTML不缓存需三步:一用fastcgi_ignore_headers Cache-Control忽略后端头;二用正则location ~* .(html|htm)$和location = /精准匹配;三在块内add_header Cache-Control "no-store,no-cache,must-revalidate,max-age=0"并expires epoch。</p>

要让 Nginx 对 HTML 页面强制不缓存,核心是确保响应头中包含 Cache-Control: no-store,且覆盖所有可能的缓存代理(包括浏览器和中间 CDN)。这不能只靠 expires 或简单 add_header 实现,必须处理好指令执行顺序、location 匹配优先级以及动态内容的干扰。
为什么普通 add_header 不生效?
Nginx 的 add_header 默认仅在响应状态码为 2xx 或 3xx 时生效;而 HTML 页面常因后端(如 PHP/FastCGI)返回 200,看似正常,但若 upstream 返回了其他 Cache-Control(比如 PHP 自己输出了 Cache-Control: public),Nginx 默认不会覆盖它。更关键的是:add_header 在 location 块中定义时,子请求或 proxy_pass 场景下会被继承或忽略,导致 header 丢失。
正确配置 no-store 的三步法
-
禁用 upstream 缓存头干扰:使用
proxy_ignore_headers Cache-Control;(反向代理场景)或fastcgi_ignore_headers Cache-Control;(PHP-FPM 场景),让 Nginx 忽略后端返回的 Cache-Control,完全由自己控制。 -
精准匹配 HTML 资源:用正则 location 匹配以
.html结尾或根路径(/)的请求,避免误伤 JS/CSS 等静态资源:location ~* \.(html|htm)$ { ... }location = / { ... } -
强制设置且确保生效:在匹配块内,用
add_header Cache-Control "no-store, no-cache, must-revalidate, max-age=0";,并添加expires epoch;(等价于max-age=0,兼容老旧浏览器)。
完整可运行示例(含 root 和 proxy 场景)
假设你用 Nginx 代理一个 PHP 应用,需同时控制 / 和 /about.html:
location / {
# 先匹配根路径,防止被后续正则覆盖
try_files $uri $uri/ /index.php?$query_string;
}
<h1>明确匹配 HTML 页面(含 .htm)</h1><p>location ~* .(html|htm)$ {
fastcgi_ignore_headers Cache-Control;
add_header Cache-Control "no-store, no-cache, must-revalidate, max-age=0";
expires epoch;
fastcgi_pass php-backend;
include fastcgi_params;
}</p><h1>根路径也需单独处理(因为 / 不匹配 .html 正则)</h1><p>location = / {
fastcgi_ignore_headers Cache-Control;
add_header Cache-Control "no-store, no-cache, must-revalidate, max-age=0";
expires epoch;
fastcgi_pass php-backend;
include fastcgi_params;
}⚠️ 注意:fastcgi_ignore_headers 必须放在 fastcgi_pass 之前才有效;add_header 要写在 fastcgi_pass 后面,否则可能不继承上下文。
立即学习“前端免费学习笔记(深入)”;
验证是否生效
部署后,用 curl 检查响应头:curl -I https://yoursite.com/
确认输出中包含:Cache-Control: no-store, no-cache, must-revalidate, max-age=0Expires: Thu, 01 Jan 1970 00:00:01 GMT
同时检查没有出现重复的 Cache-Control 行(Nginx 不会合并,重复会出错)。浏览器开发者工具 Network 标签页中,该 HTML 请求的 Size 应显示为 (from network),而非 (from disk cache) 或 (from memory cache)。


















