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;
}
相关推荐
如来神掌十八式4 小时前
nginx基础知识
运维·nginx
IT青栀菀6 小时前
Tengine替换Nginx作为代理服务遇到的问题
运维·nginx
蜜獾云7 小时前
Nginx-包教包会-入门
运维·nginx
青霄9 小时前
nginx动态匹配(分流)
nginx·动态转发
舒一笑1 天前
我把前端从 /ais 改到 /kb 后,连续踩了 7 个 Nginx 坑(含 405/413/502/404 终极解法)
运维·nginx·程序员
东北甜妹1 天前
Redis 知识总结
运维·nginx·安全
Cyber4K1 天前
【Nginx专项】基础入门篇-日志格式、日志分类、日志缓存及日志轮转
运维·服务器·nginx·缓存
观无1 天前
html+nginx实现看板
前端·nginx·html
.柒宇.2 天前
nginx入门教程
运维·nginx
如来神掌十八式2 天前
nginx + spring gateway+spring 服务_nginx 转发到 gateway
nginx·spring·gateway