【问题标题】:Why I can't put proxy_set_header inside an if clause?为什么我不能将 proxy_set_header 放在 if 子句中?
【发布时间】:2013-05-06 05:17:17
【问题描述】:

使用此配置:

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

我重新加载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

此配置工作正常,但它没有达到我想要的效果:

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

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

【问题讨论】:

标签: configuration nginx proxy


【解决方案1】:

与 proxy_pass 不同,您不能将 proxy_set_header 放在 if 块中。您只能将其放在 http/server/location 块中。所以你的第二个配置很好。

参考:http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_set_header

上下文:http、服务器、位置

不知道 $request 变量是什么。它没有出现在 nginx 变量列表中:http://wiki.nginx.org/HttpCoreModule#Variables。您想在这里实现什么目标?

【讨论】:

  • 我要做的是:“如果定义了 cookie 'mycookie',则将原始 URL 放在标头中并将请求发送到另一台服务器”
  • 然后用$request_uri代替$request
  • 好的,但这并不能解决问题。您知道添加该标题的任何方法吗?我还尝试了 add_header 指令但没有成功nginx.org/en/docs/http/ngx_http_headers_module.html#add_header
  • 什么症状?您没有在代理的上游服务器中看到 X-Request 标头吗? add_header 是在响应中添加header,proxy_set_header 是在请求​​中添加header。它们用于不同的目的。
  • 与 proxy_set_header (在 if 之外)效果很好。使用 add_header 它不会。但我只想在 cookie 存在时添加标题
【解决方案2】:

在内部位置尝试这样的事情

# default header value in a new variable
set $esb "$remote_addr, $host";

# if my custom header exists
if ($http_my_header){
  set $esb "$http_my_header, $remote_addr, $host";
}

proxy_set_header my-header $esb;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-24
    • 1970-01-01
    • 2020-01-31
    • 2014-05-19
    • 2021-01-14
    • 2017-12-01
    • 2020-11-01
    相关资源
    最近更新 更多