Overwriting URIs on nginx does not work when using variables

I have this mapping:

map $id $backend_host {
    default http://primary-host;
    1 http://primary-host;
    2 http://secondary-host;
}

And the following locations:

location / {
  set $id 1;
  proxy_pass $backend_host;
}

location /second/ {
  set $id 2;
  proxy_pass $backend_host/;
  rewrite ^/second(.*)$ $1 break;
}

And when sending to http://nginx-host/second/some/uriI see that it falls into the second sentence of the location, the URI is rewritten, but then it is proxied to the primary host instead of the secondary.

On the other hand, when I set the second location as follows:

location /second/ {
  proxy_pass http://secondary-host/;
  rewrite ^/second(.*)$ $1 break;
}

That is, without using variables, it works fine.

Could not find anything in documents that explain this.

+4
source share
1 answer

try it

map $id $backend_host {
    default primary-host;
    1 primary-host;
    2 secondary-host;
}

location / {
  set $id 1;
  proxy_pass http://$backend_host;
}

location /second/ {
  set $id 2;
  proxy_pass http://$backend_host/;
  rewrite ^/second(.*)$ $1 break;
}

http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_pass

or even so:

proxy_pass $ request;

, , , .

:

0

Source: https://habr.com/ru/post/1615534/


All Articles