nginx: Why I can't put proxy_set_header inside an if clause?

With this configuration:

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

I have this error when I reload nginx service:

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

This configuration works OK, but it does not do what I want:

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

Why I can't put proxy_set_header directive inside an if clause?


Assuming you actually meant to ask, 'how can I get this to work', how about just re-writing so the header is always passed, but has it set to some ignored value if you don't want it set.

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

'If' is generally a bad practive in nginx configuration. You can use map module to make things work. see http://nginx.org/en/docs/http/ngx_http_map_module.html http://wiki.nginx.org/HttpMapModule