proxy_cache_bypass 用于让特定请求跳过缓存直接转发后端,须与 proxy_cache 成对出现在 location 块中,变量名严格小写转下划线(如 X-Refresh → $http_x_refresh),值非空且不为 "0"/"off" 时生效,并推荐配合 proxy_no_cache 防止缓存污染。

proxy_cache_bypass 不是“清缓存”,而是让特定请求跳过缓存查找,直接转发到后端。它生效的前提、写法和配合项都必须准确,否则配置等于没写。
必须和 proxy_cache 成对出现在 location 块中
单独写 proxy_cache_bypass 没有效果。Nginx 只有在启用缓存的 location 里才会识别这个指令。例如:
- ✅ 正确:location /api/ { proxy_pass http://backend; proxy_cache mycache; proxy_cache_valid 200 5m; proxy_cache_bypass $http_x_refresh; }
- ❌ 错误:只在 server 或 http 块里写 proxy_cache_bypass,但对应 location 没有 proxy_cache
- ⚠️ 注意:mycache 必须和 proxy_cache_path 中定义的 keys_zone 名称一致
变量名要严格按规则转换
客户端发送 X-Refresh: 1,Nginx 内部对应变量是 $http_x_refresh,不是 $http_X_Refresh 或 $http_xrefresh。规则是:
FastAPI + Flask 混合部署最佳实践,解决路由定义、API 代理等常见问题,适用于同时运行 FastAPI API 与 Flask 前端的场景。
- 全小写
- 短横线 - 替换为下划线 _
- 固定前缀 $http_
- 常见对照:X-Admin-Bypass → $http_x_admin_bypass,X-Gray-Preview → $http_x_gray_preview
值判断逻辑:非空且不等于 "0" 或 "off"
只要变量展开后满足以下任一条件,就触发绕过:
- 值是非空字符串(如 "1"、"true"、"force"、"debug")
- 值不是 "0"(不区分大小写)
- 值不是 "off"(不区分大小写)
- 示例有效请求:
curl -H "X-Refresh: true" /api/data、curl -H "X-Refresh: T" /api/data - 示例无效请求:
curl /api/data(无 Header)、curl -H "X-Refresh: 0" /api/data
务必搭配 proxy_no_cache 防止缓存污染
proxy_cache_bypass 只控制“不读缓存”,默认仍会把响应写入缓存(只要状态码匹配 proxy_cache_valid)。如果管理员带 Token 请求用户数据,响应被缓存,后续普通用户可能误命中。
- 推荐配对使用:
proxy_cache_bypass $http_x_refresh;和proxy_no_cache $http_x_refresh; - 两个指令用同一个变量,确保既不读旧缓存,也不存新响应
- 尤其适用于带鉴权头(如 $http_authorization)或调试参数(如 $arg_debug)的场景
验证是否生效,看响应头中 X-Cache-Status: BYP,或日志中 $upstream_cache_status 字段为 BYP,而不是 HIT 或 MISS。

















