You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何免费清理Nginx fcgi_cache中指定URL或全部缓存?

免费清理Nginx fcgi_cache的方案

针对你用fcgi_cache加速网站,需要免费清理指定URL或全部缓存的需求,给你几个实用方案:

1. 直接删除磁盘缓存文件(无需额外模块)

fcgi_cache的缓存以文件形式存在磁盘上,直接找到对应文件删除即可:

  • 清理全部缓存:先找到Nginx配置中fcgi_cache_path指定的路径(比如/var/cache/nginx),执行命令:

    sudo rm -rf /var/cache/nginx/*
    

    注意:确保执行命令的用户有足够权限,或者用su - nginx切换到Nginx运行用户后执行。

  • 清理指定URL缓存:Nginx默认的缓存key是$scheme$request_method$host$request_uri,先生成对应URL的key,再定位文件删除。比如要清理https://example.com/about:

    # 生成缓存key(这里假设请求方法是GET,根据实际情况调整)
    CACHE_KEY=$(echo -n "httpsGETexample.com/about" | md5sum | cut -d' ' -f1)
    # 根据fcgi_cache_path的levels参数(比如levels=1:2)定位文件
    find /var/cache/nginx -name "${CACHE_KEY:0:1}/${CACHE_KEY:1:2}/${CACHE_KEY}" -delete
    

    如果你的Nginx配置了自定义fcgi_cache_key,要把生成key的命令改成和配置一致的规则。

2. 用开源模块ngx_cache_purge(需编译Nginx)

ngx_cache_purge是免费的第三方模块,专门用来清理缓存,步骤如下:

  1. 下载模块源码,编译Nginx时加入模块:
    ./configure --add-module=/path/to/ngx_cache_purge
    make && make install
    
  2. 在Nginx的server块中添加清理规则:
    # 清理指定URL缓存
    location ~ /purge(/.*) {
        allow 127.0.0.1;  # 仅允许本地IP访问,防止恶意操作
        deny all;
        fcgi_cache_purge fcgi_cache $scheme$request_method$host$1;
    }
    
    # 可选:清理全部缓存
    location = /purge_all {
        allow 127.0.0.1;
        deny all;
        fcgi_cache_purge fcgi_cache *;
    }
    
  3. 重启Nginx后,访问http://yourdomain.com/purge/path/to/page即可清理对应URL的缓存,访问http://yourdomain.com/purge_all清理全部缓存。

3. 用Lua脚本(适合OpenResty或带ngx_lua的Nginx)

如果你的Nginx安装了ngx_lua模块(比如OpenResty默认包含),可以写简单脚本实现缓存清理:
在server块中添加:

location /purge {
    allow 127.0.0.1;
    deny all;
    content_by_lua_block {
        local cache_root = "/var/cache/nginx"  # 替换成你的缓存路径
        local target_uri = ngx.var.arg_uri

        if target_uri then
            # 生成缓存key,和Nginx的fcgi_cache_key规则一致
            local cache_key = ngx.md5("httpsGET" .. ngx.var.host .. target_uri)
            local cache_file = cache_root .. "/" 
                .. string.sub(cache_key, 1, 1) .. "/" 
                .. string.sub(cache_key, 2, 3) .. "/" 
                .. cache_key
            os.remove(cache_file)
            ngx.say("已清理缓存: ", target_uri)
        else
            # 清理全部缓存
            os.execute("rm -rf " .. cache_root .. "/*")
            ngx.say("已清理全部缓存")
        end
    }
}

使用时:

  • 清理指定URL:访问http://yourdomain.com/purge?uri=/path/to/page
  • 清理全部缓存:直接访问http://yourdomain.com/purge

注意事项

  • 无论用哪种方案,都要限制清理接口的访问权限(比如仅允许本地IP或可信IP),避免被恶意利用。
  • 确保Nginx进程对缓存目录有读写权限,否则清理操作会失败。

内容的提问来源于stack exchange,提问作者Alijvhr

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 15:32:16