08 server 与 location 的查找


 TL;DR
一个请求怎么找到该走的虚拟主机和 location:Host 头如何选出 server、location 的四类形态与匹配顺序、if 在哪个阶段求值、try_files 落在哪个 phase。行号基于 nginx 1.31.11。
难度 中等

上一章把配置文件变成了一棵树。这一章是那棵树第一次真正被用上的时刻:
一个请求进来,它凭什么挑中某个 server{},又凭什么挑中某个 location{}?

读完之后你应该能回答:

  1. Host: a.com 是怎么变成「用哪个 server{}」的判断的?找不到会怎样?
  2. location 为什么分成精确、前缀、正则、命名四类?查找顺序是什么?
  3. location = /a 和 location /a 差在哪一步?
  4. if 是什么时候求值的?为什么 server{} 里的 if 和 location{} 里的 if 不是一回事?
  5. try_files 落在哪个 phase?它是怎么把请求「改道」的?

本文所有行号基于 /work/ai/cwork/nginx,版本是 nginx 1.31.11
(mainline,HEAD e76b6746c)。

8.1 一个请求的查找路线

整条路线只有三步:

客户端请求
    │
    ├─ ① Host 头 → server{}
    │     ngx_http_process_host()  request.c:1866
    │     ngx_http_set_virtual_server()     :2475
    │
    ├─ ② uri → location{}
    │     find_config_phase() → find_location()  :1446
    │     → r->loc_conf 换成它的
    │
    └─ ③ 按 phase 跑:SERVER_REWRITE → FIND_CONFIG →
          REWRITE → … → PRECONTENT → CONTENT
          if 在 REWRITE 段求值,try_files 在 PRECONTENT 段

两步的关键区别:第一步换的是 r->srv_conf 和 r->loc_conf(整台 server 的),
第二步换的只是 r->loc_conf(单个 location 的)
。

8.2 第一步:选中虚拟主机

8.2.1 Host 头从哪来

Host 头由 ngx_http_process_host()(src/http/ngx_http_request.c:1866)处理:
先判重(src/http/ngx_http_request.c:1874,两个 Host 头直接 400),再校验
合法性(ngx_http_validate_host(),src/http/ngx_http_request.c:2277),
最后调 ngx_http_set_virtual_server()(src/http/ngx_http_request.c:2475)选主机。
请求行里带 host 的写法(GET http://a.com/ HTTP/1.1)已在
src/http/ngx_http_request.c:1197 选过一次,这里不重复选。

选中之后,ngx_http_set_virtual_server()
(src/http/ngx_http_request.c:2475)把两个指针换掉:
r->srv_conf = cscf->ctx->srv_conf、r->loc_conf = cscf->ctx->loc_conf
(src/http/ngx_http_request.c:2546-2547)。

r->loc_conf 先被设成 server 级别的 loc_conf —— 这就是「还没选 location」
时的初始状态,location{} 的配置此时还没生效。

8.2.2 哈希查表,正则兜底

ngx_http_set_virtual_server() 内部调 ngx_http_find_virtual_server()
(src/http/ngx_http_request.c:2558),先查哈希表:

// src/http/ngx_http_request.c:2568-2575
    cscf = ngx_hash_find_combined(&virtual_names->names,
                                  ngx_hash_key(host->data, host->len),
                                  host->data, host->len);

    if (cscf) {
        *cscfp = cscf;
        return NGX_OK;
    }

哈希表是启动时建好的:ngx_http_server_names()
(src/http/ngx_http.c:1594)遍历每个 server{} 的 server_name 数组,用
NGX_HASH_WILDCARD_KEY 把 *.example.com 这类通配名也收进去
(src/http/ngx_http.c:1637-1639);重名的名字会打一条警告(src/http/ngx_http.c:1651-1655)。

哈希没查到,才轮到正则 server_name(~^...$)挨个试
(src/http/ngx_http_request.c:2620-2634)。两者都没命中就是
NGX_DECLINED,此时不换 r->srv_conf(src/http/ngx_http_request.c:2542),
请求落到这个监听地址的默认 server 上。

坑:server_name 是先转小写再进哈希表的
(src/http/ngx_http_core_module.c:4601-4603),查表用 ngx_hash_key_lc
(src/http/ngx_http.c:1659);但正则的 server_name 大小写敏感 ——
只有模式里自带大写字母时才触发 NGX_REGEX_CASELESS
(src/http/ngx_http_core_module.c:4627-4632)。

另一个坑:server_name 只有 *. 开头的通配和 . 开头的写法合法,
*foo.com 会被 ngx_http_core_server_name()(src/http/ngx_http_core_module.c:4555)
直接判成 invalid。

8.3 location 为什么分四类

location 的语法分成四类,靠前缀修饰符区分:

写法 记号 落到哪个字段 什么时候用
location = /a 精确 exact_match = 1 只接 /a 这一个 uri
location /a 前缀 默认(inclusive) 接所有以 /a 开头的 uri
location ^~ /a 前缀 noregex = 1 接 /a 开头,且不再试正则
location ~ ^/a 正则 regex 交给 PCRE 匹配
location @name 命名 named = 1 只能被内部跳转命中

=、^~、~、~* 的判读在 ngx_http_core_location()
(src/http/ngx_http_core_module.c:3163)里:

// src/http/ngx_http_core_module.c:3217-3225
        if (len == 1 && mod[0] == '=') {

            clcf->name = *name;
            clcf->exact_match = 1;

        } else if (len == 2 && mod[0] == '^' && mod[1] == '~') {

            clcf->name = *name;
            clcf->noregex = 1;

同一个函数里还有两种不靠修饰符的写法(src/http/ngx_http_core_module.c:3281-3302):
以 $ 开头的是谓词(location $var { ... }),记在 predicate 字段;
以 @ 开头的是命名 location,记在 named 字段。

这些标志都住在 ngx_http_core_loc_conf_t(src/http/ngx_http_core_module.h:314)里。

8.3.1 为什么要分四类

因为它们查找代价完全不同:精确和前缀走红黑树(static_locations),对数时间;
正则走线性遍历(regex_locations),要挨个跑 PCRE;谓词只是读一个变量的值。

所以 nginx 把它们分开放,查找时先便宜的、后贵的。建树在
ngx_http_init_locations()(src/http/ngx_http.c:671):先用
ngx_http_cmp_locations()(src/http/ngx_http.c:971)排序,规则里写死了
「命名、谓词、正则统统排到最后」(src/http/ngx_http.c:998-1040),然后
分别装进三个数组(src/http/ngx_http.c:756-833),剩下的静态 location
再由 ngx_http_init_static_location_trees()(src/http/ngx_http.c:835)建树。

8.4 location 的匹配算法

8.4.1 先查静态树

ngx_http_core_find_location()(src/http/ngx_http_core_module.c:1446)
是入口,它第一件事就是查红黑树:

// src/http/ngx_http_core_module.c:1456-1460
    noregex = 0;

    pclcf = ngx_http_get_module_loc_conf(r, ngx_http_core_module);

    rc = ngx_http_core_find_static_location(r, pclcf->static_locations);

ngx_http_core_find_static_location()(src/http/ngx_http_core_module.c:1545)
在树上一路比较,命中时按「精确」还是「前缀」返回不同结果:

// src/http/ngx_http_core_module.c:1598-1608
        if (len == (size_t) node->len) {

            if (node->exact) {
                r->loc_conf = node->exact->loc_conf;
                return NGX_OK;

            } else {
                r->loc_conf = node->inclusive->loc_conf;
                return NGX_AGAIN;
            }
        }

四个返回值的含义写在这个函数上方的注释里(src/http/ngx_http_core_module.c:1537-1542):

返回值 含义 后果
NGX_OK 精确命中 用这个 location,收工
NGX_AGAIN 前缀命中(inclusive) 先记下,再找嵌套 location
NGX_DONE 命中带斜杠的自动重定向 回 301(src/http/ngx_http_core_module.c:1612-1617)
NGX_DECLINED 没命中 继续往下试正则

NGX_AGAIN 那一支很关键:前缀命中不是终点,nginx 会继续往下找嵌套的
location(src/http/ngx_http_core_module.c:1468-1471)。

8.4.2 再试正则,最后试谓词

静态树没命中(NGX_DECLINED)或者嵌套里也没命中,才轮到正则:
noregex == 0 && pclcf->regex_locations 时挨个跑 ngx_http_regex_exec()
(src/http/ngx_http_core_module.c:1481-1488),命中就把 r->loc_conf
换成它、再递归找它的嵌套 location(src/http/ngx_http_core_module.c:1490-1498)。

noregex 为真就跳过整段正则 —— 这正是 ^~ 的作用(src/http/ngx_http_core_module.c:3222-3225)。

正则也没命中,才轮到谓词 location:pclcf->predicate_locations 挨个读变量值
(src/http/ngx_http_core_module.c:1509-1521)。predicate 存的是变量下标 + 1
(src/http/ngx_http_core_module.c:3293),取值时要 -1 还原;变量值为空
或 "0" 就算不匹配。

命名 location 不在查找链上 —— 它只能被内部跳转命中,查找代码在
ngx_http_named_location()(src/http/ngx_http_core_module.c:2677)里。

整个算法画成图:

uri = "/a/b/c"
    │
    ├─ ① 静态树(红黑树)
    │     精确 "=" 命中? → NGX_OK,结束
    │     前缀命中?     → NGX_AGAIN,记下,继续找嵌套
    │     没命中?       → NGX_DECLINED
    │
    ├─ ② 嵌套 location(递归调用自己)→ 找到就结束
    ├─ ③ 正则(顺序试 PCRE,^~ 则整段跳过)
    └─ ④ 谓词(读变量值)
          都不中 → 落到 server 级 loc_conf

坑:location = /a 和 location /a 的差别不在「匹配」,
而在匹配之后还要不要继续往下找。= 命中即返回 NGX_OK;/a 命中
返回 NGX_AGAIN,nginx 会继续在 /a 里面找嵌套 location,
也会先试正则(前缀命中不代表最终胜出)。
所以 location /a 和 location ~ /a/b 并存时,/a/b 落到正则那个。

8.5 if 什么时候求值

if 不是一个 location —— 它是 rewrite 模块的一条指令
(src/http/modules/ngx_http_rewrite_module.c:531):造一个匿名的伪
location
(clcf->noname = 1)、把块里的指令编译成脚本码、
求值时条件成立就把 r->loc_conf 换成这个伪 location 的。

第 1 步在 ngx_http_rewrite_if() 里:

// src/http/modules/ngx_http_rewrite_module.c:581-588
    clcf = ctx->loc_conf[ngx_http_core_module.ctx_index];
    clcf->loc_conf = ctx->loc_conf;
    clcf->name = pclcf->name;
    clcf->noname = 1;

    if (ngx_http_add_location(cf, &pclcf->locations, clcf) != NGX_OK) {
        return NGX_CONF_ERROR;
    }

第 3 步在 ngx_http_script_if_code()(src/http/ngx_http_script.c:1608):
条件成立就把 r->loc_conf 换成 code->loc_conf
(src/http/ngx_http_script.c:1619-1626),不成立就跳过整块(src/http/ngx_http_script.c:1632)。

什么时候求值?rewrite 模块在 postconfiguration 里把同一个处理器注册到
两个 phase(src/http/modules/ngx_http_rewrite_module.c:271):

// src/http/modules/ngx_http_rewrite_module.c:279-284
    h = ngx_array_push(&cmcf->phases[NGX_HTTP_SERVER_REWRITE_PHASE].handlers);
    if (h == NULL) {
        return NGX_ERROR;
    }

    *h = ngx_http_rewrite_handler;

同一个处理器还被注册进 NGX_HTTP_REWRITE_PHASE
(src/http/modules/ngx_http_rewrite_module.c:286-291)。

  • 写在 server{} 里的 if:在 SERVER_REWRITE_PHASE 求值 ——
    这时还没选 location;
  • 写在 location{} 里的 if:在 REWRITE_PHASE 求值,location 已选好。

两条 if 的差别就在 if_code->loc_conf 是不是 NULL
(src/http/modules/ngx_http_rewrite_module.c:613-620):server 级的是 NULL,
条件成立时不换 r->loc_conf;location 级的是真指针,所以会换。

坑:server{} 里的 if 不能用来决定「用哪个 location」——
它跑的时候 location 还没选,它能做的是改 $uri、改响应码。
想要「按条件选 location」,正解是 map 配 try_files,
或者用 location $var { } 这种谓词 location。

8.6 try_files 落在哪

try_files 落在 PRECONTENT_PHASE。注册在
ngx_http_try_files_init()(src/http/modules/ngx_http_try_files_module.c:405):

// src/http/modules/ngx_http_try_files_module.c:410-419
    cmcf = ngx_http_conf_get_module_main_conf(cf, ngx_http_core_module);

    h = ngx_array_push(&cmcf->phases[NGX_HTTP_PRECONTENT_PHASE].handlers);
    if (h == NULL) {
        return NGX_ERROR;
    }

    *h = ngx_http_try_files_handler;

    return NGX_OK;

它在 PRECONTENT 里做的事分两种。

① 前面的候选文件存在 → 改写 r->uri,然后 NGX_DECLINED 放行,让后面的
内容处理器(通常是 static 模块)去发这个文件
(src/http/modules/ngx_http_try_files_module.c:294-299)。
② 候选全都不存在 → 走最后一个候选,它有两种走法:

// src/http/modules/ngx_http_try_files_module.c:219-229
            if (path.data[0] == '@') {
                (void) ngx_http_named_location(r, &path);

            } else {
                ngx_http_split_args(r, &path, &args);

                (void) ngx_http_internal_redirect(r, &path, &args);
            }

            ngx_http_finalize_request(r, NGX_DONE);
            return NGX_DONE;
  • 以 @ 开头 → 跳到命名 location(src/http/ngx_http_core_module.c:2677),
    整个请求重来一遍;
  • 普通路径 → 内部重定向(src/http/ngx_http_core_module.c:2622),
    URI 变了,于是 location 要重新选一遍。

至于 =code 那种写法(try_files $uri =404)最简单:解析时就把状态码存进 tf->code
(src/http/modules/ngx_http_try_files_module.c:366-378),命中时直接返回
(src/http/modules/ngx_http_try_files_module.c:212-214)。

坑:try_files 的内部重定向会让 location 重新查找一遍 ——
POST_REWRITE_PHASE 发现 r->uri_changed 置位,就把 r->phase_handler 打回
FIND_CONFIG(src/http/ngx_http_core_module.c:1109-1112)。所以 try_files 里
写的路径不该是又能被某个 location 匹配上的 URI,否则会绕回去;
nginx 用 r->uri_changes 计数来防死循环(src/http/ngx_http_core_module.c:1098-1107)。

8.7 phase 全景

11 个 phase 定义在 src/http/ngx_http_core_module.h:110-129;本篇相关的几个:

phase 谁在里面 说明
SERVER_REWRITE rewrite 模块 server{} 里的 if、rewrite
FIND_CONFIG core 模块 选 location(src/http/ngx_http_core_module.c:980)
REWRITE rewrite 模块 location{} 里的 if、rewrite
POST_REWRITE core 模块 uri 变了就跳回 FIND_CONFIG 重选
PRECONTENT try_files try_files 落在这里
CONTENT 各内容模块 static / proxy / fastcgi ……

FIND_CONFIG 这一格是本篇的核心,它的第一句就是选 location
(src/http/ngx_http_core_module.c:988-998):先 r->uri_changed = 0,再
ngx_http_core_find_location(r),之后 r->loc_conf 就是这个 location 的配置了。

8.8 小结

  • 虚拟主机:Host 头 → ngx_http_set_virtual_server() → 哈希查表 → 正则兜底 → 都不中就落默认 server。
  • 四类 location:精确 =、前缀(含 ^~)、正则 ~/~*、命名 @;
    谓词 $var 是第五种。建树时便宜的在前、贵的在后。
  • 匹配顺序:静态红黑树 → 嵌套 location(递归)→ 正则 → 谓词;
    ^~ 用 noregex 掐断正则那一段。
  • 前缀命中不等于最终胜出:NGX_AGAIN 之后还要继续找嵌套和正则。
  • if 是 rewrite 模块的指令,编译成脚本码;server{} 里的在 SERVER_REWRITE
    求值,location{} 里的在 REWRITE 求值。
  • try_files 在 PRECONTENT:命中就改 r->uri 放行,不中就内部重定向或跳
    命名 location,触发 location 重选。

参考

  • 源码树:/work/ai/cwork/nginx(nginx 1.31.11,HEAD e76b6746c)
  • 关键落点:src/http/ngx_http_request.c(Host 头与虚拟主机)、
    src/http/ngx_http_core_module.c(location 查找、phase checker)、
    src/http/ngx_http.c(建树与合并)、src/http/ngx_http_script.c(if 求值)
  • 官方文档:Request processing

文章作者: growdu
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 growdu !
  目录