关键是要用 fastcgi_no_cache 配合动态条件变量精准跳过缓存,而非简单关闭;需基于 URL 路径、Cookie、请求方法等识别隐私请求,并配置 fastcgi_ignore_headers 和 PHP 缓存头确保生效。

要防止包含用户隐私路径的动态页面被错误缓存到 FastCGI 共享内存区,关键不是简单关闭缓存,而是用 fastcgi_no_cache 配合精准条件变量,让 Nginx 主动拒绝写入缓存——尤其避免不同用户看到彼此的私密内容(如个人中心、订单列表、消息页等)。
必须识别并标记隐私路径请求
不能靠文件后缀(如 .php)一刀切,而要基于 URL 路径、请求方法、Cookie 或请求头特征动态判断:
- 匹配常见隐私路径:
/user/、/account/、/my/orders、/api/profile、/wp-admin/、/dashboard/ - 检查是否含登录态标识:
$http_cookie ~* "PHPSESSID|wordpress_logged_in|auth_token" - 识别敏感操作:非 GET/HEAD 请求(如 POST 提交表单、PUT 修改资料)
- 若有可信身份头(如网关透传的
X-Auth-Role: user),也可直接用$http_x_auth_role = "user"判断
在 PHP 处理块中设置跳过逻辑
确保该逻辑位于 location ~ \.php$ 内,且在 fastcgi_pass 之前:
set $skip_cache 0;
if ($request_uri ~* "^/(user|account|my/orders|api/profile|wp-admin|dashboard)") {
set $skip_cache 1;
}
if ($http_cookie ~* "(PHPSESSID|wordpress_logged_in|auth_token)") {
set $skip_cache 1;
}
if ($request_method !~ ^(GET|HEAD)$) {
set $skip_cache 1;
}
fastcgi_no_cache $skip_cache;
fastcgi_cache_bypass $skip_cache;补充关键防御配置
- 在
http{}块全局添加:fastcgi_ignore_headers Cache-Control Expires Set-Cookie;
(防止后端 PHP 输出的Set-Cookie或Cache-Control: private导致缓存策略混乱) - 确保隐私接口 PHP 脚本自身输出明确无缓存头:
header('Cache-Control: no-cache, no-store, must-revalidate'); - 若使用 CDN,同步对
/user/、/account/等路径设置「不缓存」策略,避免边缘节点误存
验证是否真正生效
用 curl 检查响应头:
curl -I https://yoursite.com/user/profile
应看到:
-
X-FastCGI-Cache: BYPASS(或MISS,但绝不能是HIT) - 响应头含
Cache-Control: no-cache - 无
Set-Cookie被忽略后导致的缓存污染(可通过日志log_format cache '$remote_addr - $upstream_cache_status $request';确认 VIP 或用户请求始终为BYPASS)
不复杂但容易忽略

















