最清晰可控的方式是在location块中用add_header指令设置cache-control,按资源类型精准配置:带哈希静态资源设public,max-age=31536000,immutable;普通静态资源设public,max-age=2592000;html设no-cache,must-revalidate;关键场景需加always参数覆盖上游头;避免与expires混用。

直接在 location 块里用 add_header 指令写明 Cache-Control 值,是最清晰、最可控的方式。它不依赖后端,也不需要开启 proxy_cache,只负责告诉浏览器“怎么缓存这个响应”。
按资源类型精准设置 Cache-Control
不同文件对缓存的要求差异很大,统一配容易出问题:
- 带哈希的静态资源(如
app.a1b2c3.js、style.8f9e0d.css):内容不变则路径不变,适合长期强缓存add_header Cache-Control "public, max-age=31536000, immutable"; - 普通静态资源(如
logo.png、font.woff2):变动少但无哈希,设中长期缓存并保留验证能力add_header Cache-Control "public, max-age=2592000"; - HTML 文件(
index.html或根路径/):必须禁用强缓存,否则新 JS/CSS 不生效add_header Cache-Control "no-cache, must-revalidate";
注意 always 参数覆盖上游头
如果后端(比如 PHP、Node.js 或上游代理)已经返回了 Cache-Control,Nginx 默认不会覆盖它。要确保你的配置生效,加 always:
下载 Comet AI 浏览器,体验由 Perplexity AI 驱动的革命性上网方式。内置 AI 助手可实时总结网页、跨标签页对比信息、自动执行任务。告别繁琐操作,让 AI 成为你的浏览副驾,大幅提升研究与工作效率。支持 Windows、macOS、Android 和 iOS。
add_header Cache-Control "no-cache" always;
尤其适用于 HTML、登录页、API 等需强制控制的场景。
避免和 expires 混用导致误解
expires 会自动生成 Expires 和基础 Cache-Control: max-age=xxx,但它无法添加 public、immutable、must-revalidate 等关键指令。两者共存时,Cache-Control 优先级更高,但逻辑易混乱。建议:
- 只用
add_header主控,更透明; - 若需兼容老旧客户端,可额外加
expires 1y;,但非必需; - 不要同时写
expires 1h;和add_header Cache-Control "max-age=3600",冗余且易错。
常见敏感场景的典型配置
不是所有资源都适合 public 缓存:
- 含用户数据的接口(如
/api/user):add_header Cache-Control "private, max-age=300"; - 支付或登录页(
/login、/checkout):add_header Cache-Control "no-store, no-cache, must-revalidate"; - API 列表页(内容可能更新但不实时):
add_header Cache-Control "no-cache, max-age=0";










