You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Nginx Proxy Pass配置问题求助:URL转发不符合预期

Nginx反向代理路径匹配问题解决思路

当前配置失效的核心原因:location /stat 匹配请求后,Nginx会自动把/stat之后的路径片段直接追加到proxy_pass的目标地址后,导致实际转发的URL变成 http://456.com/stat/api/abc?a=123,多了多余的/stat前缀,不符合预期。

提供两种可行的解决方法:

方法一:用rewrite规则移除前缀

修改配置,通过rewrite将请求URL中的/stat前缀去掉后再转发:

server {
    listen         80;
    server_name    123.com;
    location /stat {
        rewrite ^/stat(.*)$ $1 break;
        proxy_pass http://456.com;
    }
}

rewrite ^/stat(.*)$ $1 break 会把/stat/api/abc这类路径替换为/api/abc,再转发到目标地址,完美匹配期望的URL结构。

方法二:利用Nginx路径自动替换特性

调整location和proxy_pass的末尾斜杠,让Nginx自动剥离前缀:

server {
    listen         80;
    server_name    123.com;
    location /stat/ {
        proxy_pass http://456.com/;
    }
}

这里location路径带末尾斜杠,proxy_pass也带末尾斜杠。当请求http://123.com/stat/api/abc?a=123时,Nginx会把/stat/之后的api/abc拼到http://456.com/后面,生成正确的转发URL。

补充:兼容不带斜杠的/stat请求

如果需要处理http://123.com/stat这类不带末尾斜杠的请求,可以额外添加一个精准匹配的location:

location = /stat {
    rewrite ^ http://123.com/stat/ permanent;
}

将不带斜杠的请求重定向到带斜杠的版本,确保路径匹配逻辑一致。

内容的提问来源于stack exchange,提问作者Eric Wu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 19:27:37