14

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?

Sven
  • 98,649
  • 14
  • 180
  • 226
Neuquino
  • 303
  • 2
  • 5
  • 11
  • Please don't cross-post. http://stackoverflow.com/questions/16500594/why-i-cant-put-proxy-set-header-inside-an-if-clause – ceejayoz May 11 '13 at 19:14
  • I opened a chat to discuss about this. We can continue the discussion there: http://chat.stackexchange.com/rooms/8745/nginx – Neuquino May 12 '13 at 14:54

2 Answers2

18

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;
        }
    }
Danack
  • 1,216
  • 1
  • 16
  • 27
  • 1
    You mean `""`, right? – Michael Hampton May 12 '13 at 02:33
  • 2
    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. – Danack May 12 '13 at 02:51
  • 1
    According to this article: https://www.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. – Chau Chee Yang May 03 '19 at 03:23
  • Danack thank you, it works. @MichaelHampton and thank you, yes it is!! :) – Jacky Supit Jul 21 '22 at 14:09
0

'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

Drew Khoury
  • 4,637
  • 8
  • 27
  • 28