# 重新编译Nginx添加模块
./configure --add-module=../ngx_cache_purge-X.X
make && make install
http {
# 定义缓存路径
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m max_size=10g inactive=60m;
server {
location / {
proxy_pass http://backend;
proxy_cache my_cache;
}
# 清理缓存配置
location ~ /purge(/.*) {
allow 127.0.0.1;
allow 192.168.0.0/16;
deny all;
proxy_cache_purge my_cache $scheme$proxy_host$1$is_args$args;
}
}
}
# 清理特定URL缓存
curl -X PURGE http://example.com/purge/api/data
# 清理带参数的URL
curl -X PURGE "http://example.com/purge/api/data?id=123"
server {
location / {
proxy_pass http://backend;
proxy_cache my_cache;
# 通过特定header绕过缓存
proxy_cache_bypass $http_cache_purge;
}
}
# 添加header强制刷新缓存
curl -H "Cache-Purge: 1" http://example.com/api/data
# 查找缓存文件
find /var/cache/nginx -type f -name "*" | grep "example.com"
# 删除特定域名的缓存
find /var/cache/nginx -type f -name "*example.com*" -delete
# 清空整个缓存目录
rm -rf /var/cache/nginx/*
#!/bin/bash
# purge_cache.sh
CACHE_DIR="/var/cache/nginx"
PURGE_URL=$1
# 根据URL生成缓存key
CACHE_KEY=$(echo -n $PURGE_URL | md5sum | awk '{print $1}')
# 构建缓存文件路径
CACHE_FILE="${CACHE_DIR}/$(echo $CACHE_KEY | cut -c1-2)/$(echo $CACHE_KEY | cut -c3-4)/$CACHE_KEY"
# 删除缓存文件
if [ -f "$CACHE_FILE" ]; then
rm -f "$CACHE_FILE"
echo "Purged: $PURGE_URL"
else
echo "Cache not found: $PURGE_URL"
fi
location /purge {
internal;
content_by_lua_block {
local cache = ngx.shared.cache_dict
local key = ngx.var.arg_key
if key then
cache:delete(key)
ngx.say("Purged: " .. key)
else
ngx.say("Error: key parameter required")
end
}
}
location /api {
# 正常缓存配置
proxy_cache my_cache;
proxy_cache_key $uri$args;
}
http {
proxy_cache_path /data/nginx/cache levels=1:2
keys_zone=api_cache:100m
max_size=10g
inactive=24h
use_temp_path=off;
upstream backend {
server 127.0.0.1:8080;
}
server {
listen 80;
server_name example.com;
# API接口缓存
location ~ ^/api/ {
proxy_pass http://backend;
proxy_cache api_cache;
proxy_cache_key "$scheme$request_method$host$request_uri";
proxy_cache_valid 200 302 10m;
proxy_cache_valid 404 1m;
add_header X-Cache-Status $upstream_cache_status;
}
# 缓存清理接口(受保护)
location ~ /admin/purge(/.*) {
# 访问控制
allow 127.0.0.1;
allow 10.0.0.0/8;
deny all;
# 使用purge模块
proxy_cache_purge api_cache "$scheme$request_method$host$1$is_args$args";
# 或者使用Lua
# content_by_lua_file /usr/local/nginx/lua/purge.lua;
}
# 批量清理
location /admin/purge-all {
allow 127.0.0.1;
deny all;
content_by_lua_block {
os.execute("find /data/nginx/cache -type f -delete")
ngx.say("All cache purged")
}
}
}
}
# 安全清理示例
#!/bin/bash
# 只允许从管理服务器调用
if [ "$REMOTE_ADDR" != "10.0.0.100" ]; then
exit 1
fi
# 清理并记录日志
PURGE_URL=$1
echo "$(date): Purged $PURGE_URL" >> /var/log/nginx/purge.log
curl -s "http://localhost/admin/purge$PURGE_URL"
选择哪种方式取决于:
对于生产环境,推荐使用ngx_cache_purge模块+Lua脚本的组合方式,既能保证安全性,又能提供灵活的清理策略。