nginx : Http Response code for redirected request's response

2.9k views Asked by At

We use nginx as reverse proxy. We would like nginx to follow redirects from proxy and use the Location header on 302. I could get this working using intercepting errors(proxy_intercept_errors on) and following the redirects using the Location header when 302 is received from upstream server. However, the http response code for this response is still 302. I tried both the browser and curl. Is this an expected behavior? Posted the relevant config. Hope this helps.

   server   {  
      location /      {  
         proxy_intercept_errors on; 
                error_page 302 @handle_redirects;
      }      location @handle_redirects      {  
         set $redirect_upstream_http_location $upstream_http_location; 
            proxy_pass $redirect_upstream_http_location;
      }
   }

Thanks

1

There are 1 answers

1
Tarun Lalwani On

Change your config to below

   server   {  
      location /      {  
         proxy_intercept_errors on; 
                error_page 302 301 307 = @handle_redirects;
      }
      location @handle_redirects      {  
         set $redirect_upstream_http_location $upstream_http_location; 
            proxy_pass $redirect_upstream_http_location;
      }
   }

From nginx documentation

Furthermore, it is possible to change the response code to another using the “=response” syntax, for example:

error_page 404 =200 /empty.gif; If an error response is processed by a proxied server or a FastCGI/uwsgi/SCGI server, and the server may return different response codes (e.g., 200, 302, 401 or 404), it is possible to respond with the code it returns:

error_page 404 = /404.php;