Nginx反向代理配置去掉前缀

TrumanWong
3/17/2022
TrumanWong

Nginx反向代理的时候,设置proxy_pass请求只会替换域名,如果要根据不同的url后缀来访问不同的服务,则需要通过如下方法:

方法一:加“/”

server {
    listen              80;
    server_name         trumanwl.com;

    location ^~ /test/ {
        proxy_set_header Host $host;
        proxy_set_header  X-Real-IP        $remote_addr;
        proxy_set_header  X-Forwarded-For  $proxy_add_x_forwarded_for;

        proxy_pass http://test.trumanwl.com/;
    }
}

^~ /test/表示匹配前缀是test的请求,proxy_pass的结尾有/, 则会把/test/*后面的路径直接拼接到后面,即移除test

方法二:rewrite

server {
    listen              80;
    server_name         trumanwl.com;

    location ^~ /test/ {
        proxy_set_header Host $host;
        proxy_set_header  X-Real-IP        $remote_addr;
        proxy_set_header  X-Forwarded-For  $proxy_add_x_forwarded_for;

        rewrite ^/test/(.*)$ /$1 break;
        proxy_pass http://test.trumanwl.com;
    }
}

proxy_pass结尾没有/rewrite重写了url