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

前提(事实):如果指定了带有 URIproxy_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_passURI会超出他自己的的context,同根locationURI,也就是/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;
}
相关推荐
oscar9991 小时前
3.4 Nginx 负载均衡——动态再平衡的反人性纪律
nginx·github·负载均衡·财富源代码
川石课堂软件测试3 小时前
性能测试|Nginx中间件监控与调优
linux·python·nginx·中间件·单元测试·压力测试·harmonyos
m0_7408596213 小时前
Nginx进行配置文件拆分(以windows解压版为例)
nginx
开发小程序的之朴15 小时前
认识安企CMS-安装安企CMS的环境要求
nginx·golang·系统架构
考虑考虑1 天前
nginx配置ssl
运维·后端·nginx
至乐活着1 天前
ELK日志系统从零搭建到实战:Nginx日志采集与可视化全攻略
nginx·elk·elasticsearch·docker·日志系统
激情的学姐2 天前
【大型网站技术实践】初级篇:借助Nginx搭建反向代理服务器
运维·nginx
2501_943782352 天前
【共创季稿事节】摇骰子:用 ArkTS 实现随机动画与交互反馈
运维·nginx·交互·harmonyos·鸿蒙·鸿蒙系统
开发小程序的之朴2 天前
认识安企CMS - 系统概述
nginx·golang·系统架构
小蜗牛的路2 天前
使用OpenSSL生成本地证书https+nginx
网络协议·nginx·https