尝试清除缓存时,ngx_cache_purge 出现 412 前提条件失败

尝试清除缓存时,ngx_cache_purge 出现 412 前提条件失败

我是新手,刚开始使用 nginx 做我的业余项目。现在我想安装并使用ngx_cache_purge模块https://github.com/nginx-modules/ngx_cache_purge,因为它与 wordpress 有一些很酷的集成。

这是我提出的 docker 镜像:

FROM nginx:1.18.0

RUN apt update && apt install -y --no-install-recommends  --no-install-suggests \
            wget gcc make zlib1g-dev libpcre3-dev

RUN mkdir -p /home/nginx && cd /home/nginx && \
    wget -qO - https://nginx.org/download/nginx-1.18.0.tar.gz | tar zxfv - && \
    wget -qO - https://github.com/nginx-modules/ngx_cache_purge/archive/refs/tags/2.5.1.tar.gz | tar zxfv -

RUN cd /home/nginx/nginx-1.18.0 && \
    ./configure --add-dynamic-module=../ngx_cache_purge-2.5.1 --with-compat && \
    make modules && \
    cp objs/ngx_http_cache_purge_module.so /usr/lib/nginx/modules/ 

以下是 nginx 配置示例:

load_module modules/ngx_http_cache_purge_module.so;

http {
    gzip off;
    gzip_vary off;
    gzip_proxied off;
    gzip_comp_level 6;
    gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

    proxy_cache_path /var/cache/nginx/proxy_cache levels=1:2 use_temp_path=off keys_zone=proxycache:256m
    inactive=30d
    max_size=4g;

    proxy_cache_purge PURGE from 127.0.0.1;

    server {
        listen *:8008;
        location ~* /purgea(/.*) {
            add_header X-url-match $scheme${request_method}my_proxy_server$1$args always;
            proxy_cache_purge proxycache $scheme${request_method}my_proxy_server$1$args;
            cache_purge_response_type json;
        }
    }
}

以下是缓存文件存在的确认:

root@a65be2e6f69c:/# grep -R -a -E "^KEY:" /var/cache/nginx/proxy_cache/ | grep "jquery.min.js?ver=3.6.0"
/var/cache/nginx/proxy_cache/b/3c/e0ec9b13973d56a5780010cadccc73cb:KEY: httpGETmy_proxy_server/wp-includes/js/jquery/jquery.min.js?ver=3.6.0
root@a65be2e6f69c:/# 

这是我发出的清除该 uri 缓存的请求:

root@a65be2e6f69c:/# curl -v localhost:8008/purgea/wp-includes/js/jquery/jquery.min.js?ver=3.6.0
> GET /purgea/wp-includes/js/jquery/jquery.min.js?ver=3.6.0 HTTP/1.1
> Host: localhost:8008
> User-Agent: curl/7.64.0
> Accept: */*
> 
< HTTP/1.1 412 Precondition Failed
< Server: nginx
< Date: Fri, 13 May 2022 01:04:17 GMT
< Content-Type: text/html; charset=UTF-8
< Content-Length: 166
< Connection: keep-alive
< X-url-match: httpGETmy_proxy_server/wp-includes/js/jquery/jquery.min.jsver=3.6.0
< 
<html>
<head><title>412 Precondition Failed</title></head>
<body>
<center><h1>412 Precondition Failed</h1></center>
<hr><center>nginx</center>
</body>
</html>
* Connection #0 to host localhost left intact
root@a65be2e6f69c:/#

答案1

我不明白proxy_cache在没有指令的情况下缓存是如何工作的。在我的例子中,使用 proxy_cache_purge 将 proxy_cache_key 添加到位置很有帮助。proxy_cache_key有一个默认值,但这不适用于proxy_cache_purge,您需要自己设置。

相关内容