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;
}
相关推荐
陈希1239 小时前
Nginx 从入门到能扛事:反向代理、负载均衡与 HTTPS 实战
nginx·https·负载均衡
木头左1 天前
【Nginx】内网服务源 IP 白名单实战:动态域名解析放行网段 + 端口接管零改造
运维·nginx·白名单·反向代理
skywalk81631 天前
把 去也网站 从 Ubuntu 搬到 FreeBSD:一次 Service Jail + nginx 的部署实录
linux·运维·nginx·ubuntu·freebsd
没差c1 天前
winsw将jar、nginx等注册为Windows服务
windows·nginx·jar
Lsetea3 天前
Docker更新SSL证书后容器仍读旧文件:单文件挂载与目录挂载排查
运维·nginx·docker·https·ssl证书
枫叶轻语5 天前
【Nginx 从入门到实战 09】前后端统一入口:部署页面与接口的完整配置
nginx·全栈
无言听风雨丶5 天前
Nginx 深度实战:从架构原理到生产排错
运维·nginx·架构
xxwl5855 天前
Nginx 基础学习笔记
笔记·学习·nginx
fb_123455 天前
K8s StatefulSet五大有状态集群实战_Nginx_Etcd_Redis_Cassandra_MySQL
nginx·kubernetes·etcd
acd120095 天前
域名解析缓存带来的隐性故障,很多排查都漏掉了这一层
java·运维·nginx