使用Nginx重定向到动态主机

问题描述 投票:0回答:1

我已经使用Nginx作为负载平衡器和反向代理取得了成功,但是这个看起来很简单的问题使我绊倒了。我花了几个小时尝试配置Nginx,但是失败了。

我有一组动态的服务器/主机名(由于使用了docker),例如service2,service3,service5。我只想配置nginx以根据URL代理这些。这样做的目的是让我可以从单个端点访问服务,而不是公开所有服务。

这是我尝试使用的代理类型

如果我指定了所有端点,尽管它仍然仅适用于初始页面,但它仍然有效,因此http://localhost:8009/service2确实代理了http://service2/,但是http://localhost:8009/service2/home只是失败了,但这是因为它无法匹配位置。如果我只是做定位/工作,那么我只能将所有请求反向代理到单个服务器。

server {
listen       80;
server_name  localhost;

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

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

这里可能是我将URL重新动态化为最佳的最佳示例,但这只是错误,因此假设它对nginx无效。

server {
listen       80;
server_name  localhost;

    location ~ (?<myhost>.*)/(?<myuri>.*)$ {
        proxy_pass http://$myhost/$myuri;
    }
}
docker nginx nginx-location nginx-reverse-proxy nginx-config
1个回答
0
投票

您使用的正则表达式不正确。您可以通过以下方式实现您想做的事情

 location ~ /(?<myhost>[^/]+)(/(?<myuri>.*))? {
      return 301 http://$myhost:80/$myuri?$query_string;
    }
➜  ~   curl --head http://127.0.0.1:32769/service1
HTTP/1.1 301 Moved Permanently
Server: nginx/1.17.8
Date: Sun, 23 Feb 2020 20:06:29 GMT
Content-Type: text/html
Content-Length: 169
Connection: keep-alive
Location: http://service1:80/?

➜  ~   curl --head http://127.0.0.1:32769/service1/test
HTTP/1.1 301 Moved Permanently
Server: nginx/1.17.8
Date: Sun, 23 Feb 2020 20:08:43 GMT
Content-Type: text/html
Content-Length: 169
Connection: keep-alive
Location: http://service1:80/test?

➜  ~   curl --head http://127.0.0.1:32769/service1/test?x=100
HTTP/1.1 301 Moved Permanently
Server: nginx/1.17.8
Date: Sun, 23 Feb 2020 20:08:53 GMT
Content-Type: text/html
Content-Length: 169
Connection: keep-alive
Location: http://service1:80/test?x=100

对于proxy_pass,您不需要包括URI或查询字符串,您可以像这样进行操作

server {
    listen       80  default_server;
    server_name  _;

    location ~ /(?<myhost>[^/]+) {
        resolver 127.0.0.11 ipv6=off;

        set $target http://$myhost:80;

        proxy_set_header Host $myhost;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_pass $target;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.