17

I have an nginx proxy_pass setup to pass every request on /api through to a backend Tomcat REST service. This service in some cases returns a Location header which varies according to the type of request, e.g., Location: http://foo.bar/baz/api/search/1234567 -- the baz part is due to it being hosted on Tomcat.

My current configuration rewrites the foo.bar host name correctly, but leaves the baz part intact. I'd like to strip this, but the proxy_pass options seem to be limited to clearing or setting a new value for the header.

Is there a way to modify headers dynamically before being passed on to the client, using a regex substitute, for instance? This is my nginx configuration:

location /api {
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

    proxy_max_temp_file_size 0;
    client_max_body_size    10m;
    client_body_buffer_size 128k;
    proxy_connect_timeout   90;
    proxy_send_timeout      90;
    proxy_read_timeout      90;
    proxy_buffers           32 4k;
    proxy_redirect off;

    proxy_pass http://foo.bar:8080/baz/api;
}
user2010963
  • 297
  • 1
  • 3
  • 8

1 Answers1

32

You may be able to use regexp to modify it but a better way is to use a proxy redirect:

proxy_redirect http://foo.bar/baz/ /;

http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_redirect

Any Location headers for foo.bar/baz/ will go to /

If you just want to redirect /baz/api, that'll work too.

If any redirects are also adding the port, you'll need to add http://foo.bar:8080/baz/ as well (separate redirect).

Hope this helps!

dbreaux
  • 4,982
  • 1
  • 25
  • 64
Chelsea Urquhart
  • 1,388
  • 1
  • 11
  • 18
  • 3
    Thanks for your response, but I'm not so much interested in redirecting (which is working fine), but in modifying the `Location` header which is returned as a server response. The API returns a `Location` header containing the URL where the client is supposed fetch the results of its previous query. This is now pointing to a faulty location because the server doesn't know it's being proxied. – user2010963 Jan 21 '14 at 16:59
  • 1
    proxy_redirect modifies the Location header... That's the purpose of it. Take a look at the nginx docs (http://wiki.nginx.org/HttpProxyModule#proxy_redirect) :) – Chelsea Urquhart Jan 27 '14 at 00:39
  • 1
    Oh, I see! That did indeed do it. Thank you! (Although I do think `redirect` isn't the best name for what it actually does) – user2010963 Feb 02 '14 at 01:02
  • 1
    Agreed! I think proxy_rewrite or something like that would make so much more sense lol – Chelsea Urquhart Feb 02 '14 at 11:54
  • @ChelseaUrquhart How do I modify only certain part of the URL and not the whole URL? – Krunal Aug 28 '20 at 06:14