Nginx用proxy_pass重写

时间:2020-09-17 21:14:49

标签: nginx

最近,我在Nginx中要求重写URL,然后将其转发到另一台后端服务器上,以到达动态代理传递地址。我已经尝试了一些方法,但是目前还没有很多运气。例如,这是我在nginx.conf文件中设置的那种类型:

server {
  listen 443;
  server_name scheduler.domain-name;
  rewrite ^scheduler(.*)/(.*)/(.*) $2$1$3; # scheduler.domain.local/changepass/report?target=service
...

location / {
  proxy_pass $to-rewrite-address:9443; # changepass.domain.local/report?target=service
  ...
}

本质上,我只需要使用重写的URL变量即可在其他端口上转发请求,但看不到它可以正常工作。

尽管我了解使用代理传递变量(Dynamic proxy_pass to $var with nginx 1.0时必须设置DNS解析器),但我已经做了很多搜索,但还没有找到解决方案。

非常感谢有人可以建议如何实现上述目标,非常感谢。

1 个答案:

答案 0 :(得分:0)

假设始终将端点指定为URI的第一部分,这是一个应该起作用的配置示例:

server {
    listen 443;
    server_name scheduler.domain-name;
    resolver <your resolver for domain.local>;
    ...
    location ~ ^/(?<endpoint>changepass|endpoint2|endpoint3|...)(?<route>/.*) {
        proxy_pass http://$endpoint.domain.local:9443$route;
    }
}

为了更好的可读性,我在这里使用命名捕获组,该位置块等于

    location ~ ^/(changepass|endpoint2|endpoint3|...)(/.*) {
        proxy_pass http://$1.domain.local:9443$2;
    }

我不确定查询参数是否会以这种结构保留,如果不能保留,请更改

proxy_pass http://$endpoint.domain.local:9443$route;

proxy_pass http://$endpoint.domain.local:9443$route$is_args$args;