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
Related videos on Youtube
Comments
-
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?
-
ceejayoz about 11 yearsPlease don't cross-post. stackoverflow.com/questions/16500594/…
-
Neuquino about 11 yearsI opened a chat to discuss about this. We can continue the discussion there: chat.stackexchange.com/rooms/8745/nginx
-
-
Michael Hampton about 11 yearsYou mean
""
, right? -
Danack about 11 yearsI 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 about 5 yearsAccording 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.