如何清理Nginx的fastcgi PHP缓存?
美国、香港服务器
如何清理Nginx的fastcgi PHP缓存?
11-17 来源:
## 1、先加上 PURGE 配置(http 块,nginx.conf)
fastcgi_cache_path /www/cache/fcgi levels=1:2 keys_zone=fcgi_cache:20m max_size=1g inactive=60m;
geo $purge_allow {
default 0;
127.0.0.1 1;
}
map $request_method $purge_method {
PURGE $purge_allow;
default 0;
}
## 2、站点 server 块(网站 Nginx 配置,PHP 站点)
server {
listen 80;
server_name example.com;
# PHP location
location ~ \.php$ {
fastcgi_pass unix:/tmp/php-cgi-74.sock;
fastcgi_cache fcgi_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;
}
}
校验重载:
nginx -t && nginx -s reload
## 3、SSH 命令清理【指定单个 URL】(最常用)
# 清理 https://example.com/index.php
curl -X PURGE https://example.com/index.php
# 带GET参数URL(引号不能丢)
curl -X PURGE "https://example.com/list.php?page=1"
返回 `204 No Content` = 清理成功
返回 `404 Not Found` = 该 URL 没有缓存
开源免费 Nginx:`curl -X PURGE https://example.com/api/*` 只是内存标记失效,**不会自动删除磁盘文件**;商业版 Nginx Plus 的 purger=on 才会扫描删除通配缓存nginx
## 4、一键清空全部 FastCGI 缓存(整站全部缓存,慎用)
先确认你的缓存目录:上面配置是 `/www/cache/fcgi`
rm -rf /www/cache/fcgi/*
nginx -s reload
## 5、宝塔自带缓存插件(不是自己写 fastcgi_cache)
宝塔【网站】→【设置】→【缓存】,如果是**宝塔静态缓存插件**,面板直接输入 URL 刷新,不用写 PURGE 配置。
## 6、批量清理脚本(多个 URL)
#!/bin/bash
URLS=(
"https://example.com/index.php"
"https://example.com/about.php"
"https://example.com/list.php?page=1"
)
for u in "${URLS[@]}";do
echo "清理:$u"
curl -X PURGE "$u"
echo "-----"
done
## 7、踩坑清单(PHP 缓存高频问题)
1. `fastcgi_cache_key` 和 purge 时不一致,永远清不掉(比如缓存带 `$request_method`)
2. 前面套 Cloudflare:**PURGE 只能清源站 Nginx 缓存,CF 缓存要单独在 CF 后台刷新 URL**
3. 先验证缓存是否生效:
curl -I https://example.com/index.php
看响应头 `X-Cache-Status: HIT` 才代表有缓存
4. 安全狗 / 防火墙拦截:只能本机 127.0.0.1 执行 curl PURGE
## 8、备选方案(不想改配置)
直接删除缓存目录文件,缺点:**不能精准清单个 URL,只能全清**
三二互联专业提供香港VPS,美国VPS主机,香港云服务器租用等业务香港美国到大陆CN2 GIA速度最快