vikasap
vikasap

Reputation: 3

Rewrite a URL while resetting a request header - nginx

I am trying to rewrite a relative URL "/A" to "/B", while also setting the request header. The url /A is already exposed to some clients. /B is essentially /A with the Accept header set to "json". I am trying to remove /A support from the upstream and just have /B in the upstream. But I need to continue to support /A. Hence the problem

I am able to rewrite successfully however the header does not get set.


location = /A {
   proxy_set_header Accept "json"
   rewrite /A /B;
}

location = /B {
  ... a lot of configurations here ...
  proxy_pass http://my_upstream;
}

The following works for me, but I see that nginx makes an additional request to itself which is not so cool.

location = /A {
   proxy_set_header Accept "json"
   proxy_pass http://127.0.0.1:$server_port/B;
}

location = /B {
  ... a lot of configurations here ...
  proxy_pass http://my_upstream;
}

Any suggestions ?

Upvotes: 0

Views: 2483

Answers (1)

Ivan Shatsky
Ivan Shatsky

Reputation: 15470

location = /A {
   set $accept "json";
   rewrite /A /B;
}

location = /B {
    proxy_set_header Accept $accept;
    ... a lot of configurations here ...
    proxy_pass http://my_upstream;
}

nginx won't set the header at all if an empty string passed as proxy_set_header second parameter. And if your request will not be captured by location = /A block, $accept variable would have an empty value at location = /B block.

Update

Configuration given above will clear an Accept HTTP header if the request is captured by the second location block. If you want to preserve it, you can use more complex configuration:

map $accept $accept_header {
    ""       $http_accept;
    default  $accept;
}

server {

    ...

    location = /A {
        set $accept "json";
        rewrite /A /B;
    }

    location = /B {
        proxy_set_header Accept $accept_header;
        ... a lot of configurations here ...
        proxy_pass http://my_upstream;
    }

    ...

}

Upvotes: 1

Related Questions