Search code examples
if-statementnginxproxyurl-rewritingproxypass

nginx if directive changes url in proxy_pass


I am trying to use nginx to proxy to a secure download by setting an auth token as a cookie and then proxying with an additional header (<a href=""> doesn't let me set headers). I have found that the if directive is rewriting the url.

if ($http_cookie ~* "X-Auth-Token=(.+?)($|;)") {
}
proxy_pass http://127.0.0.1:5555/static;

When sending a GET request with /private/foo.ext it gets proxied to: /static/private/foo.ext.

If I comment out the if directive:

# if ($http_cookie ~* "X-Auth-Token=(.+?)($|;)") {
# }
proxy_pass http://127.0.0.1:5555/static;

When sending a GET request with /private/foo.ext it gets proxied to: /static/foo.ext.

The full code looks like this:

if ($http_cookie ~* "X-Auth-Token=(.+?)($|;)") {
    set $auth_token $1;
}
proxy_pass http://127.0.0.1:5555/static;
proxy_set_header X-Auth-Token $auth_token;
proxy_pass_request_header on;

But I commented out everything except the if directive and that seems to be what is changing the url.

Why is it adding /private in the url in one case and not the other? I want it to remove /private from the path.

Edit: nginx version is 1.6.0.


Solution

  • Per the above suggestion, I abandoned using if in favor of map. Here is the final result that is now working.

    map $http_cookie $auth_token {
        "~.*?X-Auth-Token=(?<token>.*)(;|$)" $token;
    }
    
    location /private {
        proxy_set_header X-Auth-Token $auth_token;
        proxy_pass_request_headers on;
        proxy_pass http://127.0.0.1:5555/static;
    }