关键在于让Nginx明确识别并跳过动态响应:通过set变量$skip_cache统一标记Session页、POST请求及敏感路径,再成对配置fastcgi_cache_bypass与fastcgi_no_cache指令,二者缺一不可,配合响应头和日志验证绕过效果。
关键不是“防缓存”,而是“让 Nginx 明确知道哪些响应不该进缓存”——fastcgi_no_cache 本身不阻止缓存,它只是告诉 Nginx:当变量值为非空(或非零)时,当前请求的响应体不要写入缓存区。真正起作用的是它与 fastcgi_cache_bypass 配合形成的双重判断逻辑。
Session 相关页面(如登录后首页、个人中心、评论提交页)通常通过 Cookie 或 URL 参数暴露状态。需用 Nginx 变量提前捕获这些信号:
$http_cookie ~* "PHPSESSID|wordpress_logged_in|thinkphp_session_id"
$request_uri ~* "^/(wp-admin|admin|user|member|api/v1/profile)"
$request_method = POST
避免在 location 块内重复写多条 if 判断,推荐统一定义变量 $skip_cache:
set $skip_cache 0;
if ($http_cookie ~* "PHPSESSID") { set $skip_cache 1; }if ($request_method = POST) { set $skip_cache 1; }if ($request_uri ~* "/admin/") { set $skip_cache 1; }
仅写 fastcgi_no_cache 1 是无效的——Nginx 要求它必须绑定变量,且需与 fastcgi_cache_bypass 同时存在才能生效:
fastcgi_cache_bypass $skip_cache;:变量为 1 时,请求不查缓存,直接打到 PHP-FPMfastcgi_no_cache $skip_cache;:变量为 1 时,PHP 返回的响应不写入缓存区fastcgi_no_cache,Nginx 仍会读缓存(可能返回旧内容);若只设 fastcgi_cache_bypass,则新响应会被错误缓存配置生效后,可通过响应头和日志交叉确认:
X-FastCGI-Cache: BYPASS 或 MISS(而非 HIT)cache key ... skipped due to fastcgi_no_cache 类提示/www/phpenv/nginx/fastcgi_cache/ 下无对应 hash 目录生成