Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modifying a Location header with nginx proxy_pass

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;
}
like image 612
user2010963 Avatar asked Oct 24 '13 14:10

user2010963


People also ask

What does proxy_pass do in nginx?

The proxy_pass setting makes the Nginx reverse proxy setup work. The proxy_pass is configured in the location section of any virtual host configuration file. To set up an Nginx proxy_pass globally, edit the default file in Nginx's sites-available folder.

Does nginx pass headers?

NGINX takes care of known frequently used headers (list of known headers_in). It parses it and stores in the handy place (direct pointer in headers_in ). If a known header may consist of more then one value (Cookies or Cache-Control for example.) NGINX could handle it with an array.


1 Answers

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!

like image 148
Chelsea Urquhart Avatar answered Sep 16 '22 22:09

Chelsea Urquhart