Home > database >  nginx proxy_redirect does not rewrite location header in response
nginx proxy_redirect does not rewrite location header in response

Time:12-10

i have a simple problem

  • setup a load balancer using nginx for 6 upstream servers

i have done this

upstream hisservers {
ip_hash;
server A;
server B;
server C;
server D;
server E;
server F; }

server {
listen 80;
server_name test.server;
location / {
proxy_set_header X-Forwarded-Host $host:$server_port;
proxy_set_header X-Forwarded-Server $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://hisservers;
} }

but the problem is... above solution does not rewrite the Location header in reponse.. so i always get redirect to any of those 6 upstreams

then i did this

proxy_redirect http://hisservers /;

still it doesnt work finally i did this

proxy_redirect http://A/ /;
proxy_redirect http://B/ /;
proxy_redirect http://C/ /;
proxy_redirect http://D/ /;
proxy_redirect http://E/ /;
proxy_redirect http://F/ /;

and it works..

i thought that nginx by default will match the upstreams and rewrte the location header..

any tips on this..

i think my solution is quite hacky

CodePudding user response:

Each of your servers return different hostnames in their Location response headers, and so your proxy_redirect statement(s) must match these hostnames.

You can match each hostname using separate proxy_redirect statements, as you have demonstrated at the end of your question.

Alternatively, proxy_redirect allows you to use regular expressions. See this document for details.

For example:

proxy_redirect ~*http://[^/] (/.*)$ $1;

The above statement should be a substitute for the six statements at the end of your question. The [^/] expression matches any hostname, and the (/.*)$ expression captures the URI to be used in the replacement.

  • Related