如何配置fastcgi_cache_purge和proxy_cache_purge?
美国、香港服务器
如何配置fastcgi_cache_purge和proxy_cache_purge?
11-18 来源:
## 第一步:nginx.conf 的 http {} 全局块(宝塔直接粘贴到 nginx.conf 的 http 内,只写一次)
# ========= FastCGI PHP缓存 zone =========
fastcgi_cache_path /www/cache/fcgi levels=1:2 keys_zone=fcgi_zone:20m max_size=1g inactive=60m use_temp_path=off;
# ========= Proxy反向代理缓存 zone =========
proxy_cache_path /www/cache/proxy levels=1:2 keys_zone=proxy_zone:20m max_size=1g inactive=60m use_temp_path=off;
# ========= PURGE 访问控制(共用) =========
geo $purge_allow {
default 0;
127.0.0.1 1;
# 需要其他内网机器清理就加:192.168.1.0/24 1;
}
map $request_method $purge_method {
PURGE $purge_allow;
default 0;
}
缓存目录不存在先创建:`mkdir -p /www/cache/fcgi /www/cache/proxy && chown www:www /www/cache/fcgi /www/cache/proxy`
## 第二步、PHP 站点(fastcgi_cache + fastcgi_cache_purge)
网站设置 → Nginx 配置,server 块内:
server {
listen 80;
server_name demo.com;
# WordPress 跳过缓存规则(后台、登录、POST不缓存)
set $skip_cache 0;
if ($request_method = POST) { set $skip_cache 1; }
if ($request_uri ~* "/wp-admin/|/xmlrpc.php|wp-login.php") { set $skip_cache 1; }
if ($http_cookie ~* "wordpress_logged_in|comment_author") { set $skip_cache 1; }
location ~ \.php$ {
fastcgi_pass unix:/tmp/php-cgi-74.sock;
fastcgi_cache fcgi_zone;
fastcgi_cache_bypass $skip_cache;
fastcgi_no_cache $skip_cache;
# 重点:cache_key,purge必须和这个完全一致!
fastcgi_cache_key "$scheme$host$request_uri";
fastcgi_cache_valid 200 10m;
# 开启清除
fastcgi_cache_purge $purge_method;
add_header X-Cache-Status $upstream_cache_status;
fastcgi_index index.php;
include fastcgi.conf;
}
}
## 第三步、反向代理站点(proxy_cache + proxy_cache_purge)
server {
listen 80;
server_name proxy.demo.com;
location / {
proxy_pass http://127.0.0.1:8080;
proxy_cache proxy_zone;
proxy_cache_key "$scheme$host$request_uri";
proxy_cache_valid 200 10m;
proxy_cache_purge $purge_method;
add_header X-Cache-Status $upstream_cache_status;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
## 第四步:校验 + 重载
nginx -t && nginx -s reload
输出 `test is successful` 才是配置无误
## 第五步、SSH 执行清理命令(本机执行)
# fastcgi PHP页面
curl -X PURGE https://demo.com/index.php
# 带GET参数,必须加引号
curl -X PURGE "https://demo.com/list.php?page=1"
- ✅ `204 No Content`:成功,内存索引 + 缓存条目删除
- ⚠️ `404 Not Found`:该 URL 没有缓存
- ❌ `403 Forbidden`:发起请求的 IP 不在 purge 白名单
## 备选方案:GET 方式 purge 路由(老方案,适合部分程序自动清理)
不推荐和上面 PURGE method 混用,二选一
# fastcgi版本示例
location ~ /purge(/.*) {
allow 127.0.0.1;
deny all;
fastcgi_cache_purge fcgi_zone "$scheme$host$1";
}
# 调用方式 curl http://demo.com/purge/index.php
三二互联专业提供香港VPS,美国VPS主机,香港云服务器租用等业务香港美国到大陆CN2 GIA速度最快