proxy_no_cache需与proxy_cache_bypass协同作用才能动态跳过缓存:前者阻止响应写入缓存,后者跳过缓存查找;须用map统一预处理登录态、角色、路径等信号为0/1变量,并在location中成对启用两指令,任一变量为1即彻底绕过缓存。
要让 proxy_no_cache 在特定场景下真正“动态跳过缓存生成”,关键不是让它单独工作,而是让它和 proxy_cache_bypass 协同作用——前者管“不存”,后者管“不读”。只设 proxy_no_cache 1 或直接写变量,往往只能阻止响应落盘,却无法避免返回旧缓存内容。
把登录态、角色、设备、路径、参数等信号统一转为 0/1 变量,逻辑清晰、便于维护:
map $cookie_sessionid $no_cache_by_login { ~. 1; default 0; }
map $http_x_user_role $no_cache_by_role { "admin" 1; "editor" 1; default 0; }
map $request_uri $no_cache_by_path { ~*^/admin/ 1; ~*^/api/v1/debug 1; default 0; }
map $arg_nocache $no_cache_by_arg { "1" 1; "true" 1; default 0; }
两个指令要传入完全相同的变量列表,Nginx 才会按“任一为真即绕过”的逻辑统一执行:
proxy_cache_bypass $no_cache_by_login $no_cache_by_role $no_cache_by_path $no_cache_by_arg;proxy_no_cache $no_cache_by_login $no_cache_by_role $no_cache_by_path $no_cache_by_arg;只要其中任意一个变量值为 1(比如用户带了有效 session ID),整条请求就彻底脱离缓存链路。
所有 map 的 default 必须设为 0,否则空值、缺失字段或未匹配路径可能意外触发绕过:
http 块中直接写 proxy_no_cache $cookie_sessionid——空 cookie 会被视为空字符串,但 Nginx 对变量做的是“非空即真”判断,容易误判/static/、/images/、.js、.css 等静态资源路径,单独配 location,跳过上述 map 判断,专注用 expires 或 proxy_cache_valid 管理proxy_cache 已在该 location 中启用,否则 proxy_cache_bypass 和 proxy_no_cache 不生效实测时关注响应头和实际行为:
curl -H "X-User-Role: admin" https://example.com/dashboard
X-Cache: HIT,理想状态是出现 X-Cache-Status: BYP 或 X-Cache: MISS