how in nginx to redirect location to any host received urls?

Viewed 58

I need to get the host address from the request and redirect to another host with the rewritten address, but in all possible ways I failed

Here's an example (one of the attempts):

location / {
  proxy_pass http://...;
  ...
}

location /service/(.*)$/ {
  rewrite /service/$1/(.*)$ /$2 break;
  proxy_pass http://$1.localhost:8080/;
  ...
}

Works only if hardcoded:

location /service/hostaname/ {
   rewrite /service/hostaname/(.*)$ /$1 break;
   proxy_pass http://hostaname.localhost:8080/;
   ...
}

But this is not a suitable solution for me

Help meeeeeee, thanks!

1 Answers

Your location syntax is invalid, as it is missing the regular expression operator. The rewrite statement contains an invalid regular expression.

You do not need the rewrite statement as you can extract the parts of the URI from the location statement.

For example:

location ~ ^/service/([^/]+)/(.*)$ {
    proxy_pass http://$1.localhost:8080/$2;
}

You may need to define a resolver statement as the proxy_pass contains variables. See this document for details.

Related