nginx反向代理配置proxy_pass时,注意URI替换的坑

前提(事实):如果指定了带有 URI 的 proxy_pass 指令,则当请求被传递给服务器时,与location匹配的标准化请求 URI 的部分将被指令中指定的 URI 替换。

bash 复制代码
location /name/ {
    proxy_pass http://127.0.0.1/remote/;
}

在上面的例子中,如果请求URI为/name/test/,则会被替换为/remote/test/

不过在某些情况下,要替换的请求 URI 的部分无法确定:

当location使用正则时,或者在named location内部

一般来说,named location通常用于内部重定向,而不需要暴露给外部,他不带有自己的URI。

sh 复制代码
server { 
    location /root_uri { 
        # Named location 
            location @proxy {
                # Here, the URI is relative to the root location, not the current location 
                proxy_pass http://example.com/uri; 
                } 
        # Invoking the named location 
        try_files $uri @proxy; 
    } 
}

例子中,named location没有自己的URI,所以他内部proxy_pass的URI会超出他自己的的context,同根location的URI,也就是/root_uri产生联系。

这会导致不可预料的行为或者错误。

此时,不推荐named location内部的proxy_pass 写上URI

当location使用rewrite改变了URI时

下面的location使用了rewrite,所以它内部的proxy_pass不应该带有URI

sh 复制代码
location /name/ {
    rewrite    /name/([^/]+) /users?name=$1 break;
    proxy_pass http://127.0.0.1;
}

此时,要替换的请求 URI 的部分可能无法确定。

proxy_pass内部使用了变量时

sh 复制代码
location /name/ {
    proxy_pass http://127.0.0.1$request_uri;
}
相关推荐
cpolar技术支持5 小时前
服务器上的 Nginx 只想改配置却不敢动?把 Nginx-UI 跑起来,用 MCP 让 AI 助手帮你安全改配置,再用 cpolar 把面板短时开给自己
nginx·ai·cpolar·mcp·nginx-ui
春天花会开13115 小时前
内网 HTTPS 部署实战:私有 CA + Nginx 反向代理全流程复盘
运维·nginx·https
还是大剑师兰特6 天前
解决nginx错误:http://localhost:7000正常,http://localhost:7000/map 报错404
nginx·大剑师
xing-xing6 天前
Docker容器中Nginx站点根目录网页配置访问
nginx·docker
PC2005-cloud6 天前
Nginx 防盗链配置实战:用 referer 模块保护网站静态资源
nginx
PHP实战开发录6 天前
Nginx上传大文件为什么报413
nginx·php·开发
Lsetea7 天前
Nginx报No required SSL certificate was sent:mTLS客户端证书排查
运维·nginx·https·ssl·openssl
szephyr8 天前
HTTPS 证书申请与自动续期:acme.sh + Let‘s Encrypt 完整记录
nginx·https·acme.sh·证书续期
Lsetea8 天前
部署证书后提示“证书名称与输入不匹配”:Safari 报错的三层排查
nginx·https·safari·ssl证书·openssl
打工仔折腾 AI9 天前
FastAPI 从本机到生产服务器:Nginx+Gunicorn+Uvicorn 完整部署实录
人工智能·后端·python·nginx·fastapi·gunicorn