NGINX 反向代理:if 块内的 proxy_cache - 可能吗?

ano*_*one 3 scripting nginx proxy cache regex

我认为从一个小片段开始是最明智的:

    location ^~ /test/ {
            proxy_pass              http://frontend;
            proxy_http_version      1.1;
            proxy_set_header        Connection "";
            proxy_set_header        Host $host;
            proxy_set_header        X-Real-IP $remote_addr;
            proxy_set_header        X-Real-Port $server_port;
            if ( $remote_addr ~* "123.123.123.123" ) {
                    proxy_cache            cache_base;
                    proxy_cache_valid      720m;
            }
    }
Run Code Online (Sandbox Code Playgroud)

因此,本质上我们想要做的是基于条件 IF 语句设置代理缓存。

上面的方法不起作用,因为 proxy_cache 在 IF 内部无效。

有谁知道如何根据众多 nginx 内部变量之一的正则表达式匹配来代理缓存?

笔记:

我们希望基于 $remote_addr regexp 基本上禁用/启用 proxy_caching。不指定不同的 proxy_cache 值。

谢谢。

kol*_*ack 6

看来您真正想要的是将geo变量与proxy_cache_bypassproxy_no_cache结合起来:

geo $skip_cache {
  default 1;
  123.123.123.123/32 0;
  1.2.3.4/32 0;
  10.0.0.0/8 0;
}

server {
  location ^~ /test/ {
    proxy_pass              http://frontend;
    proxy_http_version      1.1;
    proxy_set_header        Connection "";
    proxy_set_header        Host $host;
    proxy_set_header        X-Real-IP $remote_addr;
    proxy_set_header        X-Real-Port $server_port;
    proxy_cache            cache_base;
    proxy_cache_valid      720m;

    # When $skip_cache is 1, the cache will be bypassed, and
    # the response won't be eligible for caching.
    proxy_cache_bypass     $skip_cache;
    proxy_no_cache         $skip_cache;
  }
}
Run Code Online (Sandbox Code Playgroud)