Configuration 为什么我能';是否将proxy\u set\u头放在if子句中?

Configuration 为什么我能';是否将proxy\u set\u头放在if子句中?,configuration,nginx,proxy,Configuration,Nginx,Proxy,使用此配置: server { listen 8080; location / { if ($http_cookie ~* "mycookie") { proxy_set_header X-Request $request; proxy_pass http://localhost:8081; } } } 重新加载nginx服务时出现以下错误: Reloading nginx configur

使用此配置:

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\u set\u header指令放入if子句中?

与proxy\u pass不同,不能将proxy\u set\u header放入if块中。您只能将其放在http/server/location块中。所以你的第二个配置很好

参考:

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


不知道$request变量是什么。它不显示在nginx变量列表中:。您想在这里实现什么?

在内部位置尝试类似的方法

# 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;

请不要越过柱子。我打开聊天室讨论这件事。我们可以在那里继续讨论。我试图做的是:“如果定义了cookie‘mycokie’,那么将原始URL放在一个头中,并将请求发送到另一个服务器”,然后使用$request_uri而不是$requestOk,但这并不能解决问题。你知道如何添加标题吗?我还尝试了add_header指令,但没有成功。症状是什么?您没有在代理的上游服务器中看到X-Request头吗?add_header是在响应中添加头,proxy_set_header是在请求中添加头。它们有不同的用途。使用proxy_set_头(在if之外)效果很好。使用add_头时,它不会。但我只想在cookie存在时添加头