nginx:为什么我不能将 proxy_set_header 放在 if 子句中?

Neu*_*ino 12 configuration nginx proxy

使用此配置:

server {
    listen 8080;
    location / {
        if ($http_cookie ~* "mycookie") {
            proxy_set_header X-Request $request;
            proxy_pass http://localhost:8081;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

重新加载 nginx 服务时出现此错误:

Reloading nginx configuration: nginx: [emerg] "proxy_set_header" directive is not allowed here in /etc/nginx/conf.d/check_cookie.conf:5
nginx: configuration file /etc/nginx/nginx.conf test failed
Run Code Online (Sandbox Code Playgroud)

此配置工作正常,但它不符合我的要求:

server {
    listen 8080;
    location / {
        proxy_set_header X-Request $request;
        if ($http_cookie ~* "mycookie") {
            proxy_pass http://localhost:8081;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

为什么我不能将proxy_set_header指令放在 if 子句中?

Dan*_*ack 15

假设您实际上是想问,“我怎样才能让它工作”,那么如何重新编写以便始终传递标头,但是如果您不想设置它,请将其设置为某个忽略的值。

server {
    listen 8080;    
    location / {
        set $xheader "someignoredvalue";

        if ($http_cookie ~* "mycookie") {
            set $xheader $request;
        }

        proxy_set_header X-Request $xheader;

        if ($http_cookie ~* "mycookie") {
            proxy_pass http://localhost:8081;
        }
    }
Run Code Online (Sandbox Code Playgroud)

  • 我个人更喜欢将东西设置为显然不是真正的值,而不是可能忘记这个 hack 已经到位,然后想知道为什么标题是空的。如果它设置为“X-Header-not-set-by-nginx”,那么你永远不会感到困惑。 (2认同)
  • 根据这篇文章:https://www.nginx.com/resources/wiki/start/topics/深度/ifisevil/。如果在位置上下文中,唯一可以在内部完成的 100% 安全的事情是返回和重写。我怀疑 if 块中的 proxy_pass 是否始终有效。 (2认同)