为API接口单独禁用缓存,需在Nginx中对/api/路径配置Cache-Control: no-store, no-cache, must-revalidate, max-age=0等响应头并加always参数强制覆盖后端头,同时统一处理OPTIONS预检请求,确保不被缓存。

为 API 接口单独禁用缓存,关键是不让浏览器或中间代理(如 CDN)存储响应,同时避免影响其他路径(如静态资源、HTML 页面)的缓存策略。Nginx 本身不缓存 API 响应(除非你显式配置了 proxy_cache),但“禁止缓存”在这里主要指**控制客户端行为**——即通过响应头告诉浏览器:别存,每次都要重发请求。
只对 /api/ 路径禁用浏览器缓存
在对应 location 块中添加标准禁用缓存头,不干扰其他规则:
- 用
^~ /api/前缀匹配,确保优先级高于泛匹配(如/) - 设置强禁用指令,覆盖任何后端可能返回的缓存头
- 对 OPTIONS 预检请求也统一处理,防止跨域预检被意外缓存
示例配置:
location ^~/api/ {
add_header Cache-Control "no-store, no-cache, must-revalidate, max-age=0" always;
add_header Pragma "no-cache" always;
add_header Expires "0" always;
<pre class='brush:php;toolbar:false;'># 若含 OPTIONS 请求,直接返回 204 并确保不缓存
if ($request_method = 'OPTIONS') {
add_header Access-Control-Allow-Origin "$http_origin" always;
add_header Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS" always;
add_header Access-Control-Allow-Headers "DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization" always;
add_header Access-Control-Allow-Credentials "true" always;
add_header Cache-Control "no-cache, no-store, must-revalidate" always;
add_header Expires "0" always;
add_header Pragma "no-cache" always;
add_header Content-Length "0" always;
add_header Content-Type "text/plain; charset=utf-8" always;
return 204;
}
proxy_pass http://backend;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;}
区分不同 API 版本做差异化控制
比如 /api/v1/ 允许缓存 1 分钟,而 /api/v2/ 完全禁用——这时不能只靠 location 嵌套,需用 map 指令动态生成缓存策略:
Linux 性能分析与调优专家,覆盖 CPU、内存、磁盘 I/O、网络、内核参数、编译优化、容器/K8s。适用场景:系统卡顿/高负载、内存不足/OOM/Swap 高、CPU 异常/iowait 高。
- 在
http块定义映射变量,根据 URI 决定缓存时长 - 在
location中引用该变量设置Cache-Control - 这样可精细控制,且不增加重复配置
示例:
http {
map $request_uri $api_cache_control {
~^/api/v1/ "public, max-age=60";
~^/api/v2/ "no-store, no-cache, must-revalidate, max-age=0";
default "no-cache";
}
<pre class='brush:php;toolbar:false;'>server {
location ^~/api/ {
add_header Cache-Control $api_cache_control always;
# 其余 proxy 配置...
}
}}
注意后端响应头是否干扰
如果上游服务已返回 Cache-Control: public, max-age=3600,Nginx 默认会透传——你加的 add_header 不会覆盖它。必须用 always 参数强制覆盖:
-
add_header Cache-Control "...";→ 仅对 2xx/3xx 响应生效,且可能被后端头覆盖 -
add_header Cache-Control "..." always;→ 对所有状态码(包括 4xx、5xx、OPTIONS)都生效,真正强制 - 若仍无效,检查是否启用了
underscores_in_headers on;或存在其他 header 过滤模块
验证是否生效
用 curl 或浏览器开发者工具查看响应头:
- 访问
/api/user,确认响应包含:Cache-Control: no-store, no-cache, must-revalidate, max-age=0Pragma: no-cacheExpires: 0 - 刷新页面后观察 Network 面板,Status 应为
200 OK(而非200 OK (from disk cache)或304) - 对 OPTIONS 请求,确认没有
Access-Control-Max-Age头(否则会被浏览器缓存预检结果)

















