proxy_no_cache 是配合 proxy_cache_bypass 使用的条件变量,值为非空且不等于"0"时跳过缓存且不缓存响应;必须用变量(如 $arg_nocache)而非字面量,常见于控制带特定参数、请求头或方法的请求不缓存。

Nginx 的 proxy_no_cache 并不是直接写在 location 块里“开启不缓存”的开关,而是配合 proxy_cache_bypass 一起控制哪些请求绕过缓存——也就是说,它本身是一个“条件变量”,值为非空或非 0 时,Nginx 才会跳过缓存,直接转发请求到后端。
理解 proxy_no_cache 的作用机制
proxy_no_cache 的值是 Nginx 变量(如 $arg_nocache、$http_cache_control 等),只要该变量的值**不为空字符串且不等于 "0"**,就表示“不走缓存”。它不会自己生效,必须和 proxy_cache、proxy_cache_bypass 配合使用。
常见误区:单独写 proxy_no_cache 1; 是无效的——因为 1 是字面量,不是变量;必须写成 proxy_no_cache $no_cache_flag; 这类带变量的形式。
在 location 中实现“特定请求不缓存”的典型配置
假设你已启用缓存(proxy_cache my_cache;),现在想让以下几类请求跳过缓存:
- 带查询参数
nocache=1的请求(如/api/data?nocache=1) - 请求头含
Cache-Control: no-cache或Pragma: no-cache - POST、PUT、DELETE 等非 GET/HEAD 请求
对应配置如下:
location /api/ {
proxy_cache my_cache;
proxy_cache_bypass $arg_nocache $http_cache_control $http_pragma $request_method;
proxy_no_cache $arg_nocache $http_cache_control $http_pragma $request_method;
# 其他 proxy_* 指令…
}
说明:
-
proxy_cache_bypass:当任一变量非空/非 0,就跳过缓存,直接发请求给后端 -
proxy_no_cache:当任一变量非空/非 0,不仅跳过缓存,还**不缓存本次响应**(即响应不会被存入 cache) -
$request_method对 POST/PUT/DELETE 返回对应方法名(如 "POST"),是非空字符串 → 触发不缓存 -
$arg_nocache在 URL 含?nocache=1时值为 "1" → 触发不缓存 -
$http_cache_control在请求头有Cache-Control: no-cache时值为 "no-cache" → 触发不缓存
按用户身份或 Cookie 控制不缓存(进阶场景)
比如:管理员请求(Cookie 中含 user_role=admin)全部不缓存。
先用 map 定义变量:
map $http_cookie $no_cache_for_admin {
default 0;
~*user_role=admin 1;
}
再在 location 中引用:
proxy_cache_bypass $no_cache_for_admin;
proxy_no_cache $no_cache_for_admin;
这样只要 Cookie 匹配到 user_role=admin,本次请求就不读缓存、也不写缓存。
验证与调试技巧
加响应头辅助判断是否命中缓存:
add_header X-Cache-Status "$upstream_cache_status";
访问时查看响应头:
-
X-Cache-Status: HIT→ 命中缓存 -
X-Cache-Status: MISS→ 未命中,但本次响应可能被缓存 -
X-Cache-Status: BYPASS→ 因proxy_cache_bypass跳过缓存(proxy_no_cache生效时也显示 BYPASS)
注意:proxy_no_cache 不影响 proxy_cache_bypass 的行为,但它决定了响应体是否会被存入缓存——BYPASS 状态下两者效果一致,但语义不同。











