nginx html目录 404 盘符_nginx配置场景分析 location /

1、准备事项说明

  • nginx 安装目录,/usr/local/nginx;
  • 1/aa.html 、2/aa.html,文件是相对 root 指令指定的路径的;
  • /usr/www/html/aa.html,是自己创建的用于测试文件;

2、现在要分析的场景是 location / {} 与 location = / {} 两种配置谁先生效,最终结果是什么,原理是什么?

2.1、第一种配置

location / {            root   html;            index  1/aa.html index.html index.htm;        }        location = / {            root   html;            index  2/aa.html index.html index.htm;        }

请求,http://192.168.135.128/,返回的是 2/aa.html 文件内容(响应结果符合预期)

1ff65b23872f3d539b0243723020f828.png

2.2、第二种配置

location / {            root   html;            index  1/aa.html index.html index.htm;        }        location = / {            root   /usr/www/html;            index  aa.html index.html index.htm;        }

请求,http://192.168.135.128/,报 404 文件找不到,查找 nginx 错误日志如下,/usr/local/nginx/html/aa.html 是该文件找不到;

(响应结果为什么是报 404 呢,不应该是精确匹配的找 /usr/www/html/aa.html 文件吗?结果不符合预期)

6b722ee7911723cd5d238ce64ffed7fb.png
2020/12/22 19:48:18 [error] 26155#0: *43 open() "/usr/local/nginx/html/aa.html" failed (2: No such file or directory),   client: 192.168.135.1, server: localhost, request: "GET / HTTP/1.1", host: "192.168.135.128"

2.3、第三种配置

location / {            root   /usr/www/html;            index  1/aa.html index.html index.htm;        }        location = / {            root   /usr/www/html;            index  aa.html index.html index.htm;        }

请求,http://192.168.135.128/,返回的是 /usr/www/html/aa.html 文件内容;(响应结果符合预期)

02a308b79497f58088bbdfc8be2aa89e.png

3、原理分析

  • 首先肯定精确匹配是优先于一般匹配的;
  • 要理解清楚 root 和 index 两个指令的含义,

1)root 指令意思是响应请求的根路径,如第二种配置,

请求 http://192.168.135.128/index.html 匹配的是一般匹配,所以 nginx 实际响应的是 html/index.html;

e017c4496438202bf2c59d2a77ec9ec4.png

2)index 指令是指当请求为【/】斜杠结尾时会用该指令配置的文件来响应请求,如第二种配置,

请求 http://192.168.135.128/index/ 匹配的是一般匹配,所以 nginx 实际响应的是 html/index/1/aa.html,但是该文件是不存在的,查看 nginx 错误日志也是符合分析的;

2a40e41de4ceb27fa4c6a2fee5f69e38.png
2020/12/22 20:17:45 [error] 26259#0: *53 "/usr/local/nginx/html/index/1/aa.html" is not found (2: No such file or directory),   client: 192.168.135.1, server: localhost, request: "GET /index/ HTTP/1.1", host: "192.168.135.128"
  • 分析第二种配置的情况,为什么是 404 呢?

请求,http://192.168.135.128/,匹配的是精确匹配,因为请求是以【/】斜杠结尾,所以 index 指令发挥作用,nginx 会在请求后加上 aa.html 并自动跳转,

即请求变为 http://192.168.135.128/aa.html,此时符合一般匹配,此时 root 指令发挥作用,nginx 实际找的是 html/aa.html ,但该文件不存在所以报 404,

查看 nginx 日志符合分析;

  • 分析第三种配置的情况,为什么又是正常的呢?

请求,http://192.168.135.128/,匹配的是精确匹配,因为请求是以【/】斜杠结尾,所以 index 指令发挥作用,nginx 会在请求后加上 aa.html 并自动跳转,

即请求变为 http://192.168.135.128/aa.html,此时符合一般匹配,此时 root 指令发挥作用,nginx 实际找的是 /usr/www/html/aa.html ,该文件存在所以响应结果正常;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值