如果主机可变,则带有新URI的nginx proxy_pass不起作用

时间:2019-01-25 20:00:10

标签: nginx nginx-location nginx-config

我正在尝试使用变量在proxy_pass中设置主机名,但是一旦尝试过,该位置之后的路径就会被忽略。

如果我尝试获取 localhost:8001 / dirA / x / y / z.html 。以下内容从http://server1:8888/dirB/dirC/x/y/z.html返回文件。这就是我期望发生的事情。

        location ^~ /dirA/ {
            proxy_pass http://server1:8888/dirB/dirC/;

但是,如果我尝试仅使用主机名变量的以下配置...,并尝试获取 localhost:8001 / dirA / x / y / z.html

        location ^~ /dirA/ {
            set $endpoint server1;
            proxy_pass http://$endpoint:8888/dirB/dirC/;

我得到了http://server1:8888/dirB/dirC/index.html的回报。

1 个答案:

答案 0 :(得分:0)

这就是proxy_pass的工作方式。如果在值中使用变量,则需要提供完整的URI。有关详情,请参见this document

您可以使用正则表达式location。例如:

location ~ ^/dirA/(.*)$ {
    set $endpoint server1;
    proxy_pass http://$endpoint:8888/dirB/dirC/$1;
}

请注意,正则表达式位置的顺序很重要。有关详细信息,请参见this document


或者,rewrite...break也应该起作用。

location ^~ /dirA/ {
    set $endpoint server1;
    rewrite ^/dirA/(.*)$ /dirB/dirC/$1 break;
    proxy_pass http://$endpoint:8888;
}
相关问题