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;
}
相关推荐
g10565591396 小时前
LAMP博客平台Wordpress实战
android·mysql·nginx·php
CDN36010 小时前
流媒体加速实践:出海东南亚短视频点播频繁缓冲,HLS 分片与 Nginx 配置调优
java·网络·nginx·流媒体加速
月落汀兰15 小时前
Linux Nginx全套实战通关|静态站点/虚拟主机/HTTPS/PHP/反向代理/七层负载均衡,每行命令逐参数拆解
linux·nginx·https
tryCbest1 天前
Vue3项目在Nginx中配置代理后端IP
nginx·vue3
就叫飞六吧1 天前
DeepSeek Harness 本地安装与启动指南
nginx
難釋懷1 天前
Nginx主动健康检查
运维·nginx
難釋懷2 天前
Nginx-Openresty
nginx·junit·openresty
qetfw2 天前
Debian 部署 Discuz! 论坛:Nginx、PHP 与 MariaDB 配置
linux·运维·nginx·debian·php·discuz
CDN3602 天前
大文件分发排坑:出海手游 APK 下载中断、速度慢,CDN 预热与后端 Nginx 优化方案
运维·前端·nginx·网络优化·大文件分发
記億揺晃着的那天2 天前
NAS 内网域名访问为什么需要浏览器授权
网络·nginx·js·nas