当 nginx 反向代理中使用变量会导致目录代理失效

梦康 2023-11-09 19:37:11 551

遇到的坑

今天遇到个小坑,当 nginx 目录级别的代理使用了变量之后,目录代理则只会代理到拼接完的目录,不会目录递归代理。

http {
    server {
        listen 80;
        server_name example.com;

        location /topic/ {
            proxy_pass https://nba.com/abc/topic/;
        }
    }
}

比如当我们访问 https://example.com/topic/abc 则会代理请求 https://nba.com/abc/topic/abc

当想通过变量来控制域名的时候,发现 https://example.com/topic/abc 则会代理请求 https://nba.com/abc/topic/

http {
    server {
        listen 80;
        server_name example.com;
        
        set $b_host  "nba.com";

        if ($host = "pre-example.com") {
            set $b_host "pre-nba.com";
        }

        location /topic/ {
            proxy_pass https://$b_host/abc/topic/;
        }
    }
}

优化方案

问题还是因为代理规则不够规范,换成^/topic/(.*)来匹配目录,则可以解决问题

http {
    server {
        listen 80;
        server_name example.com;
        
        set $b_host  "nba.com";

        if ($host = "pre-example.com") {
            set $b_host "pre-nba.com";
        }

        location ~ ^/topic/(.*) {
            proxy_pass https://$b_host/abc/topic/$1;
        }
    }
}