本地开发禁用浏览器强缓存需在响应头中明确设置Cache-Control、Pragma和Expires,并确保Nginx或DevServer不覆盖;Nginx需加always参数及proxy_ignore_headers,DevServer可配置headers或中间件,推荐按localhost等条件智能启用。

本地开发时禁用浏览器强缓存,核心是让响应头明确告诉浏览器“别存、别用”,同时确保 Nginx 或前端 DevServer 不会覆盖或忽略这些指令。
在 Nginx 中注入禁用缓存响应头
适用于你用 Nginx 做本地反向代理(比如代理 Vite/React/Vue 的 dev server),或直接托管静态资源调试:
- 在对应
location块中添加三行标准禁用头(注意大小写和语法):
add_header Cache-Control "no-store, no-cache, must-revalidate, max-age=0";<br> add_header Pragma "no-cache";<br> add_header Expires "0";
- 必须加
always参数,否则这些头只对成功响应(2xx)生效,而 304、4xx 等状态码会被跳过:add_header Cache-Control "no-store, no-cache, must-revalidate, max-age=0" always; - 如果后端(如 PHP、Node)自己返回了
Cache-Control,Nginx 默认会保留它;若想彻底接管,需配合:proxy_ignore_headers Cache-Control Expires;(放在proxy_pass之前)
在前端 DevServer 中动态控制(Vite / Webpack / Next.js)
多数现代 DevServer 已默认禁用强缓存,但可显式加固或按环境开关:
-
Vite:在
vite.config.ts的server.headers中配置:
headers: {<br> "Cache-Control": "no-store, no-cache, must-revalidate, max-age=0",<br> Pragma: "no-cache",<br> Expires: "0"<br> } -
Webpack DevServer:在
devServer.headers或devServer.before中设置:
app.use((req, res, next) => {<br> res.setHeader("Cache-Control", "no-store, no-cache, must-revalidate, max-age=0");<br> next();<br> }); -
Next.js(App Router):在路由段的
generateStaticParams外不适用;实际应通过fetch请求头或中间件控制。更推荐在middleware.ts中拦截 API 路由:
if (request.nextUrl.pathname.startsWith("/api/")) {<br> const response = await NextResponse.next();<br> response.headers.set("Cache-Control", "no-store, no-cache");<br> return response;<br> }
按开发环境智能启用(推荐进阶做法)
避免误带到预发或生产,可用 map + 条件注入,例如只对 localhost 或带 dev=true 参数的请求生效:
- 在 Nginx
http块中定义:
map $host $should_disable_cache {<br> ~^localhost 1;<br> ~^127\.0\.0\.1 1;<br> default 0;<br> } - 在
location中条件注入:
add_header Cache-Control "no-store, no-cache, must-revalidate, max-age=0" always;<br> add_header Pragma "no-cache" always;<br> add_header Expires "0" always;<br>
(仅当$should_disable_cache = 1时生效,需配合if或使用map控制整个逻辑流;注意:add_header本身不支持if,所以更稳妥的是用两个独立location分离 dev/prod)
验证是否生效
打开浏览器开发者工具 → Network 标签页 → 刷新页面 → 找到任意 HTML 或 JS 请求 → 查看 Response Headers:
- 确认存在
Cache-Control: no-store, no-cache, must-revalidate, max-age=0 - 检查
X-Cache-Status(如有)是否为BYPASS或未出现HIT - 尝试连续刷新,观察请求是否始终发出(而非显示
from disk cache或from memory cache)


















