带 Authorization 头的请求默认被 Nginx 跳过缓存,需通过 X-Cache-Status 响应头(BYP/MISS)及日志中 $upstream_cache_status 字段验证;必须同时配置 proxy_cache_bypass 和 proxy_no_cache $http_authorization,并排除后端 Cache-Control: private 干扰。

带 Authorization 头的请求默认被 Nginx 跳过缓存,这不是故障,而是安全机制。排查“绕过缓存”是否生效,关键不是看它有没有缓存,而是确认它是否按预期不进缓存、不读缓存、不写缓存。
看响应头里的 X-Cache-Status
在 Nginx 配置中提前加上:
add_header X-Cache-Status $upstream_cache_status;-
add_header X-Cache-Hit $upstream_http_x_cache_hit;(可选,辅助判断)
发起带 Authorization 的请求后,检查响应头:
- 若看到
X-Cache-Status: BYP或X-Cache-Status: MISS(且Age: 0),说明确实跳过了缓存查找 - 若出现
X-Cache-Status: HIT,说明配置未生效,请求被错误缓存了——这很危险,可能造成权限泄露
查 Nginx 日志确认行为
在 log_format 中加入缓存相关变量,例如:
-
$upstream_cache_status(记录本次是 HIT / MISS / BYP / EXPIRED) -
$http_authorization(确认头是否被正确提取)
然后用 curl 发起对比请求:
-
curl -I https://api.example.com/data(无头,应可能 HIT) -
curl -H "Authorization: Bearer abc123" -I https://api.example.com/data(有头,应显示 BYP)
对比日志中两行的 upstream_cache_status 字段,就能直观验证逻辑是否触发。
确认 proxy_cache_bypass 和 proxy_no_cache 同时启用
只配 proxy_cache_bypass $http_authorization 不够——它只跳过查找,但响应仍可能被存入缓存;必须搭配:
-
proxy_no_cache $http_authorization;(禁止写入缓存) - 两者变量值一致,且非空即为真(如
Bearer xxx是非空字符串,条件成立) - 注意变量名必须全小写:
$http_authorization,写成$http_Authorization或$http_auth都无效
排除后端干扰:检查响应头是否含 Cache-Control: private
即使 Nginx 配置正确,如果后端返回了 Cache-Control: private, no-store,Nginx 默认会尊重并跳过缓存(除非你加了 proxy_ignore_headers Cache-Control)。
- 用 curl 查看完整响应头:
curl -v -H "Authorization: Bearer xyz" https://api.example.com/xxx 2>&1 | grep "cache-control" - 若返回
private,而你又希望这类请求完全不走缓存,那 Nginx 的proxy_no_cache已足够;但若想让无鉴权请求正常缓存,就要确保后端对公开接口返回public, max-age=60


















