proxy_cache_bypass 不刷新缓存,仅使请求绕过缓存直连后端;需配合 $http_x_refresh_cache 等变量及 proxy_no_cache 实现按 Header 的逻辑跳过与响应不缓存。

proxy_cache_bypass 本身不刷新缓存,而是让请求绕过缓存直接打到后端,常被误认为“刷新”手段。真正实现基于 Header 的按需缓存跳过(即“逻辑刷新”),关键在于动态控制该指令的条件表达式。
理解 proxy_cache_bypass 的作用机制
它不删除或失效已有缓存,只决定当前请求是否走缓存路径。当表达式为真时,Nginx 跳过 cache lookup,将请求透传给 upstream;同时,该请求的响应默认也不会被缓存(除非显式配置 proxy_cache_bypass 不影响 proxy_cache_valid,且未设 proxy_no_cache)。
要达成“带特定 Header 就不走缓存”的效果,只需让该 Header 存在时表达式返回非空/非零值。
按自定义 Header 绕过缓存(例如 X-Refresh-Cache)
在 location 块中配置:
location /api/ {
proxy_pass http://backend;
proxy_cache my_cache;
proxy_cache_valid 200 5m;
<pre class='brush:php;toolbar:false;'># 当请求头包含 X-Refresh-Cache: 1 时,跳过缓存
proxy_cache_bypass $http_x_refresh_cache;
# 可选:同时禁止缓存该次响应(避免脏数据写入)
proxy_no_cache $http_x_refresh_cache;}
说明:
-
$http_x_refresh_cache自动映射请求头X-Refresh-Cache的值;若存在(即使为空字符串),Nginx 视为真值,触发 bypass - 加
proxy_no_cache是良好实践:确保带该 Header 的请求响应不会意外落盘到缓存中 - Header 名称支持下划线转横线(
X_Refresh_Cache→X-Refresh-Cache),但建议统一用横线风格
组合多个 Header 或复杂条件(如权限+调试标识)
使用 map 指令预计算布尔变量,提升可读性与复用性:
# 全局 map 块(http 级)
map $http_x_debug $bypass_cache {
"1" 1;
"true" 1;
default 0;
}
<p>map $http_authorization $bypass_for_admin {
~*^Bearer\s+admin_token 1;
default 0;
}</p><h1>在 location 中使用</h1><p>location /data/ {
proxy_pass <a href="https://www.php.cn/link/459a40cf7017c786a1112eaff835d34c">https://www.php.cn/link/459a40cf7017c786a1112eaff835d34c</a>;
proxy_cache my_cache;
proxy_cache_valid 200 10m;</p><pre class='brush:php;toolbar:false;'>set $skip_cache 0;
if ($bypass_cache) { set $skip_cache 1; }
if ($bypass_for_admin) { set $skip_cache 1; }
proxy_cache_bypass $skip_cache;
proxy_no_cache $skip_cache;}
注意:if 在 location 中可用,但应避免嵌套或过度依赖;更健壮的做法是用两个 map + geo 或第三方模块(如 ngx_http_set_misc_module)做逻辑或运算。
验证与调试技巧
快速确认是否生效:
- 用 curl 发送带 Header 请求:
curl -H "X-Refresh-Cache: 1" https://example.com/api/foo,检查响应头是否有X-Cache: MISS或X-Cache: BYPASS(需自行添加add_header X-Cache $upstream_cache_status;) - 查看 Nginx error log(调高日志级别为 info)可看到 cache lookup skipped 相关记录
- 缓存文件仍保留在磁盘,只是本次请求没读它——这不是 bug,是设计使然


















