DEBUG.WIKI
PanstarCloud:部署应用,接入 AI,云服务器与 AI 网关
晚安云;香港 CN2 ¥15/月
V.PS:让项目靠近用户,亚太、欧洲、北美 KVM VPS

解决 Nginx 报错 proxy_pass cannot have URI part in location given by regex

分析 Nginx 正则 location 中配置 URI 报错诱因,详解 rewrite 替代与去 URI 转发方案。

问题现象

在测试 Nginx 配置文件时报错中断:

nginx: [emerg] "proxy_pass" cannot have URI part in location given by regular expression, 
or inside named location, or inside the "if" block, or inside the "limit_except" block in /etc/nginx/nginx.conf:45

触发根因

Nginx 语法铁律:在正则表达式匹配的 location ~ ... 或命名的 location @name 中,proxy_pass 严禁携带任何 URI 路径部分(包括末尾斜杠 /),只能写到协议与主机端口。

解决方案

方案一:在 proxy_pass 中去掉末尾 URI 路径(保留协议和主机端口)

错误示范:

location ~ ^/api/(.*)$ {
    proxy_pass http://127.0.0.1:8080/v1/; # 带有 URI 报错
}

正确示范:

location ~ ^/api/(.*)$ {
    proxy_pass http://127.0.0.1:8080; # 纯主机端口
}

方案二:使用 rewrite 指令完成路径改写

location ~ ^/api/ {
    rewrite ^/api/(.*)$ /v1/$1 break;
    proxy_pass http://127.0.0.1:8080;
}

验证方法

执行 sudo nginx -t 测试,语法检测通过。