Nginx dynamically forwards to the implementation of upstream based on path in url


In Nginx, there are some advanced scenarios that need to be dynamically forwarded to the disabled upstream based on the path parameter in url

Scenario 1

/ svr1 xxxx & # 63; yyy forward to svr1:8080 /xxxx? yyy

/ svr2 xxxx & # 63; yyy forward to svr2:8080 /xxxx? yyy

The configuration is as follows:

location ~* /(srv[1-9]+)/(.*)$ {
  allow all;
  proxy_pass http://$1/$2$is_args$args;
  proxy_set_header Host $host;
  proxy_set_header x-forwarded-for $forwarded_addr;
}

upstream srv1 {
   server srv1-ip:8080;
}

upstream srv2 {
   server srv2-ip:8080;
}

Scenario 2

There are 3 peer services under svc1, srv1,2,3, /svc1/xxxx? yyy to srv1/2/3:8 080/xxxx? yyy

svc2 has 3 peer services srv4,5,6, /svc2/xxxx? yyy to, svr4/5/6:8080 /xxxx? yyy

location ~* /(svc[1-9]+)/(.*)$ {
  allow all;
  proxy_pass http://$1/$1/$2$is_args$args;
  proxy_set_header Host $host;
  proxy_set_header x-forwarded-for $forwarded_addr;
}

upstream svc1 {
  server srv1:8080;
  server srv2:8080;
  server srv3:8080;
}

upstream svc2 {
  server srv3:8080;
  server srv4:8080;
  server srv5:8080;
}