nginx 中 index 指令要注意的事项

2023-02-20 0 258

前段时间在做两个nginx实用性的这时候,碰到个难题,请我们先看第二个实用性:

server { listen 80; server_namewww.mos.com; access_log logs/mos.log; error_log logs/mos_error.log debug; root /home/web/www; index index.php; location = /index.php { …… }}

当出访www.mos.com时,和想像中的那样,会前述继续执行 /home/web/www 上面的 index.php。

上面再上看第三个实用性:

server { listen 80; server_namewww.abc.com; index index.html index.php; location / { root /home/web/abc/php/; } location = /index.html { root /home/web/abc/html/; }}

当中:

/home/web/abc/php 下存有 index.php。/home/web/abc/html 下存有 index.html。

此次,当出访www.abc.com时,我从前本误以为会继续执行 index.html,但前述继续执行到的看似 index.php。

他们的误会

允诺步入哪两个 location,是依照 request_uri 决定的。由于第二个实用性和他们的预期相符,所以我主观的认为 index 命令实用性的值,会附加到初始的 request_uri 后面,再去寻找 location。

以第二个例子来说,允诺www.mos.com,前述在寻找 location 时,会用 /index.php 去找。但是如果是这样的话,第三个例子在允诺www.abc.com时,应该会用index.html去找,这样就应该继续执行 index.html,但结果却不是这样的。

index命令学习

基于上面的现象,我认识到他们对 index 命令的理解存有难题,所以决定打开手册好好学习一下。

恍然大悟,总结下 index 命令会做的事情如下:

这是两个 content 阶段的命令。仅处理 request_uri 结尾为 / 的允诺。

允诺处理逻辑如下:

首先对 index 命令实用性的多个文件做顺序查找,看文件是否存有。如果存有,就结束查找过程,把这个文件附加到允诺的 request_uri 后面,并且发起两个内部的 redirect。如果全部尝试后都不存有,那么该index命令继续执行结束,nginx 会继续继续执行 content 阶段下一个命令的事情。

伪代码如下:

find = false;for(file in file_list){ if(file_exists(file)) { find = true; request_uri = request_uri + file; break; }}if(find){ redirect(request_uri);}

重新分析允诺

为了印证对 index 命令的理解,我重新编译 nginx,并将 error_log 级别设置为 debug,分析www.mos.com允诺,输出如下:

2014/07/30 17:41:11 [debug] 31021#0: *1096 rewrite phase: 02014/07/30 17:41:11 [debug] 31021#0: *1096 test location: “/index.php”2014/07/30 17:41:11 [debug] 31021#0: *1096 using configuration “”……2014/07/30 17:41:11 [debug] 31021#0: *1096 content phase: 92014/07/30 17:41:11 [debug] 31021#0: *1096 open index “/home/web/www/index.php”2014/07/30 17:41:11 [debug] 31021#0: *1096 internal redirect: “/index.php?”2014/07/30 17:41:11 [debug] 31021#0: *1096 rewrite phase: 02014/07/30 17:41:11 [debug] 31021#0: *1096 test location: “/index.php”2014/07/30 17:41:11 [debug] 31021#0: *1096 using configuration “=/index.php”

在允诺www.mos.com时,第一次并没有步入到现有的 location 中,之后在 content 阶段继续执行 index 命令,查找到实用性的 index.php 文件存有后,把 request_uri 改为 /index.php 再发起 redirect,最终步入到 location = /index.php{} 中。

有兴趣的话,我们可以自行分析我第三个实用性中www.abc.com允诺会如何做。

举报/反馈

相关文章

发表评论
暂无评论
官方客服团队

为您解决烦忧 - 24小时在线 专业服务