find_config阶段

139 阅读2分钟

find_config做的事情是,根据请求的url匹配对应的location,确定哪个location处理请求。

一、location指令的使用

location的使用有两种:

  • 使用location [=||*|^~] url {......}

  • =:为精确匹配

  • ~:大小写敏感的正则匹配

  • ~*:大小写不敏感的正则匹配

  • ^~:匹配上之后不再进行正则匹配

  • 使用location @name {......}

二、匹配优先级

nginx中有一个二叉树,用来存储所有的前缀字符串。

location的匹配顺序是:

  • 当匹配到有=的location时,就停止其他的匹配。

  • 当只匹配到一个有^~的location时,就停止其他匹配。

  • 当匹配到多个有^~的location时,使用最长匹配,即location后面跟的url最长的。

  • 当匹配到一个没有^~的location时,记住最长匹配的前缀字符串,然后按照nginx.conf中配置的顺序去匹配正则表达式,如果匹配到正则表达式,则立即使用对应的location,如果没有匹配到正则表达式,则使用最长匹配的前缀字符串。

总结:优先级顺序:= 、  ^~ 、 正则、字符串。

案例:

nginx的配置如下:

   #1
   location ~/Test1/$ {
       return 200 'first';
   }

   #2
   location ~*/Test1/(\w+)$ {
       return 200 'second';
   }

   #3
   location ^~/Test1/ {
       return 200 'third';
   }

   #4
   location /Test1/Test2 {
       return 200 'fourth';
   }

   #5
   location /Test1 {
       return 200 'fifth';
   }

  #6
   location = /Test1 {
       return 200 'exact match';
   }

1、curl http:/localhost:8000/Test1时,返回exact match%。

分析:/Test1匹配到的location有3、5、6,但是=的优先级最高,所以使用的是6.

2、curl http:/localhost:8000/Test1/时,返回third%

分析:/Test1/匹配到的location有1、3、5,匹配到^~/Test1/之后,会停止后续匹配,使用该location。

3、 curl http:/localhost:8000/Test1/Test2时,返回third%

分析:/Test1/Test2匹配到的location有2、3、4、5,但是先匹配^~,匹配到之后停止其他匹配,所以就使用^~对应的location。

4、curl http:/localhost:8000/Test1/Test2/时,返回fourth%

分析:/Test1/Test2/匹配到的location有2、3、4、5,但是先匹配^~,匹配到之后停止其他匹配,所以就使用^~对应的location。