欢迎来到徐庆高(Tea)的个人博客网站
磨难很爱我,一度将我连根拔起。从惊慌失措到心力交瘁,我孤身一人,但并不孤独无依。依赖那些依赖我的人,信任那些信任我的人,帮助那些给予我帮助的人。如果我愿意,可以分裂成无数面镜子,让他们看见我,就像看见自己。察言观色和模仿学习是我的领域。像每个深受创伤的人那样,最终,我学会了随遇而安。
当前位置: 日志文章 > 详细内容

详解nginx 中location和 proxy_pass的匹配规则

2025年04月08日 MsSqlserver
我来详细解释location和proxy_pass的作用以及它们在你的例子中的含义。location的作用location是 nginx 中用来匹配客户端请求 uri 的指令,决定如何处理特定路径的请

我来详细解释 location 和 proxy_pass 的作用以及它们在你的例子中的含义。

location 的作用

location 是 nginx 中用来匹配客户端请求 uri 的指令,决定如何处理特定路径的请求。它定义了请求的路由规则,后续的配置(如 proxy_pass)会应用在匹配的请求上。

语法

location [修饰符] 匹配模式 {
    # 配置块
}
  • 修饰符:可选,比如 =(精确匹配)、~(正则匹配)等。
  • 匹配模式:可以是具体路径、正则表达式等。

示例:location /test

location /test {
    proxy_pass http://abc.com;
}
  • 含义
    • 当客户端请求的 uri 以 /test 开头时,这个 location 块会被匹配。
    • 比如请求 http://yourdomain.com/test 或 http://yourdomain.com/test/abc 都会进入这个块。
  • uri 处理
    • 默认情况下,nginx 会把请求的完整 uri(包括 /test 部分)传递给后端,除非 proxy_pass 有特殊配置。

proxy_pass 的作用

proxy_pass 指定将请求代理到的后端服务器地址(可以是域名、ip 或上游服务器组)。它定义了请求的目标。

语法

proxy_pass 协议://目标地址;

示例:proxy_pass http://abc.com/tt

location /test {
    proxy_pass http://abc.com/tt;
}
  • 含义
    • 将匹配 location /test 的请求转发到 http://abc.com/tt
    • 后端服务器会收到转发的请求,具体 uri 取决于配置细节。

结合 location /test 和 proxy_pass http://abc.com/tt

让我解释这俩组合起来的效果:

默认行为(带路径替换)

location /test {
    proxy_pass http://abc.com/tt;
}
  • 客户端请求http://yourdomain.com/test/abc
  • 转发到后端http://abc.com/tt/abc
  • 解释
    • location /test 匹配请求的 /test 前缀。
    • nginx 会把 /test 后面的部分(/abc)保留下来。
    • proxy_pass http://abc.com/tt 指定目标地址为 http://abc.com/tt,并把剩余路径(/abc)追加到后面。
    • 最终后端收到的是 http://abc.com/tt/abc

加斜杠的效果(不替换路径)

如果在 proxy_pass 后加斜杠:

location /test {
    proxy_pass http://abc.com/tt/;
}
  • 客户端请求http://yourdomain.com/test/abc
  • 转发到后端http://abc.com/tt/abc
  • 解释
    • 加了斜杠 / 后,nginx 不会把 location 的 /test 部分替换掉,而是直接把请求的剩余路径(/abc)追加到 http://abc.com/tt/ 后面。
    • 结果和上面一样,但逻辑更明确。

不带具体路径

location /test {
    proxy_pass http://abc.com;
}
  • 客户端请求http://yourdomain.com/test/abc
  • 转发到后端http://abc.com/test/abc
  • 解释
    • 因为 proxy_pass 没有指定具体路径(只有域名),nginx 会把客户端的完整 uri(/test/abc)直接传递给后端。

常见配置模式

  • 精确匹配路径
location = /test {
    proxy_pass http://abc.com/tt;
}
  • 只匹配 http://yourdomain.com/test,不会匹配 /test/abc
  • 转发到 http://abc.com/tt(不带额外路径)。
  • 去掉前缀
location /test/ {
    proxy_pass http://abc.com/;
}
  • 请求 http://yourdomain.com/test/abc 转发到 http://abc.com/abc
  • /test/ 被去掉,只保留后面的部分。
  • 正则匹配
location ~ ^/test/(.*)$ {
    proxy_pass http://abc.com/tt/$1;
}
  • 请求 http://yourdomain.com/test/abc 转发到 http://abc.com/tt/abc
  • 使用正则捕获组 $1 动态传递路径。

总结

  • location /test:匹配以 /test 开头的请求。
  • proxy_pass http://abc.com/tt:将请求转发到 abc.com/tt,默认保留 /test 后的路径并追加到 /tt 后。
  • 关键点:是否加斜杠(/)、是否用正则,会影响路径的传递方式。

到此这篇关于nginx `location` 和 `proxy_pass`的匹配规则的文章就介绍到这了,更多相关nginx  location  和 proxy_pass匹配规则内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!