Intercepting backend 301/302 redirects (proxy_pass) and rewriting to another location block possible?

anonymous-one picture anonymous-one · Nov 27, 2013 · Viewed 37.2k times · Source

We have a couple of backends sitting behind our nginx front ends.

Is it possible to intercept 301 / 302 redirects sent by these backends and have nginx handle them?

We were thinging something alone the lines of:

error_page 302 = @target;

But I doubt 301/302 redirects can be handled the same as 404's etc etc... I mean, error_page probably doesnt apply to 200, etc error codes?

So to summarize:

Our backends send back 301/302s once in a while. We would like to have nginx intercept these, and rewrite them to another location block, where we could do any number of other things with them.

Possible?

Thanks!

Answer

Tuomo Kestilä picture Tuomo Kestilä · Sep 24, 2014

You could use proxy_redirect directive:

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

Nginx will still return 301/302 to the client but proxy_redirect will modify Location header and the client should make a new request to the URL given in the Location header.

Something like this should make the subsequent request back to nginx:

proxy_redirect http://upstream:port/ http://$http_host/;