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

http-status-code-301, http-status-code-302, nginx, redirect, reverse-proxy

Solution

You could use `proxy_redirect` directive (documentation).

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/;

Problem

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!

Original source