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

前端 未结 4 1065
悲&欢浪女
悲&欢浪女 2020-12-01 14:11

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?<

4条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-01 15:03

    I succeeded in solving a more generic case when a redirect location can be any external URL.

    server {
        ...
    
        location / {
            proxy_pass http://backend;
            # You may need to uncomment the following line if your redirects are relative, e.g. /foo/bar
            #proxy_redirect / /;
            proxy_intercept_errors on;
            error_page 301 302 307 = @handle_redirects;
        }
    
        location @handle_redirects {
            set $saved_redirect_location '$upstream_http_location';
            proxy_pass $saved_redirect_location;
        }
    }
    

    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

提交回复
热议问题