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

23,015

Solution 1

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

Solution 2

'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

Share:
23,015

Related videos on Youtube

Neuquino
Author by

Neuquino

SOreadytohelp just ask me what you want to know

Updated on September 18, 2022

Comments

  • Neuquino
    Neuquino over 1 year

    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?

  • Michael Hampton
    Michael Hampton about 11 years
    You mean "", right?
  • Danack
    Danack about 11 years
    I personally prefer to set things to be obviously not a real value, rather than potentially forgetting that this hack was in place, and then wondering why the header was empty. If it's set to "X-Header-not-set-by-nginx" then you're never going to be confused.
  • Chau Chee Yang
    Chau Chee Yang about 5 years
    According to this article: nginx.com/resources/wiki/start/topics/depth/ifisevil. The only 100% safe things which may be done inside if in a location context are return and rewrite. I doubt the proxy_pass in if block will always work.