要让Nginx通过API清除指定缓存,关键是确保purge请求精准命中目标缓存条目,这依赖于cache_key与purge key严格一致、ngx_cache_purge模块静态编译启用、以及IP白名单等可信访问控制。
要让 Nginx 通过 API 清除指定缓存,关键不是“加个 purge 接口”,而是确保每次清除请求都能精准命中目标缓存条目——这依赖于缓存键(cache key)的一致性、模块的正确启用、以及调用来源的可信控制。
原生 Nginx 不支持 PURGE 方法,需使用第三方模块 ngx_cache_purge,且仅支持静态编译:
--add-module=/path/to/ngx_cache_purge,注意匹配当前 Nginx 版本(推荐 release/v2.5+)nginx -V 2>&1 | grep -o 'cache_purge',输出含 cache_purge 才表示生效清除失败的主因是 key 不匹配。例如:
proxy_cache_key "$scheme$request_method$host$request_uri";
location ~ ^/purge(/.*)$ { proxy_cache_purge my_cache "$scheme$request_method$host$1"; }
$args),这里必须补上 $is_args$args
add_header X-Cache-Key "$scheme$request_method$host$request_uri"; 输出实际 key,与 purge 构造值比对PURGE 是高危操作,不能靠“隐藏路径”防护:
allow 10.20.0.0/16;,结尾必须加 deny all;
auth_request,对接内部 OAuth 或 JWT 校验服务清除不是删文件,而是标记缓存条目为无效。常用调用方式及状态码语义:
curl -X PURGE https://api.example.com/purge/v1/user/1001