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!
I succeeded in solving a more generic case when a redirect location can be any external URL.
Alternative approach, which is closer to what you describe, is covered in ServerFault answer to this question: https://serverfault.com/questions/641070/nginx-302-redirect-resolve-internally
More on
proxy_redirect
, for relative locationsCase
/api/
prefixSolution
If you need to follow multiple redirects, modify Vlad's solution as follows:
1) Add
to
location /
.2) Add
to the
location @handle_redirects
section.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 modifyLocation
header and the client should make a new request to the URL given in theLocation
header.Something like this should make the subsequent request back to nginx: