Nginx实现location + proxy_pass的正则解析

需求是这样子的:

访问/service--env/xxx,能够反代到env.coder4.com/service/xxx上

其实location和proxy_pass是能够支持正则的,只是有一个很诡异的限制条件:proxy_pass中不能含有/,这个没搞懂原因。

最终的实现如下:

location ~ ^/service--([^/]*)/(.*)$ {
  resolver 127.0.0.53;
  set $venv $1;
  set $new_uri /service/\;
  proxy_pass http://\.coder4.com$new_uri$is_args$args;
  proxy_set_header X-Real-IP $remote_addr;
  proxy_set_header X-Forwarded-For  $proxy_add_x_forwarded_for;
  proxy_set_header X-Forwarded-Proto $scheme;
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *