nginx `location` 和 `proxy_pass`的匹配规则

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


location 的作用

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

语法

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

示例:location /test

location /test {
    proxy_pass http://abc.com;
}
  • 含义
    • 当客户端请求的 URI 以 /test 开头时,这个 location 块会被匹配。
    • 比如请求 http://yourdomain.com/testhttp://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 /testproxy_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)直接传递给后端。

常见配置模式

  1. 精确匹配路径
location = /test {
    proxy_pass http://abc.com/tt;
}
  • 只匹配 http://yourdomain.com/test,不会匹配 /test/abc
  • 转发到 http://abc.com/tt(不带额外路径)。
  1. 去掉前缀
location /test/ {
    proxy_pass http://abc.com/;
}
  • 请求 http://yourdomain.com/test/abc 转发到 http://abc.com/abc
  • /test/ 被去掉,只保留后面的部分。
  1. 正则匹配
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 后。
  • 关键点:是否加斜杠(/)、是否用正则,会影响路径的传递方式。
posted @ 2025-04-08 11:37  仁义礼智信的  阅读(1127)  评论(0)    收藏  举报