nginx  location 匹配命令

 

 ~   #表示执行一个正则匹配,区分大小写

 ~*  #表示执行一个正则匹配,不区分大小写

 ^~  #表示普通字符匹配,如果该选项匹配,只匹配该选项, 不匹配别的选项,一般用来匹配目录

 =   #进行普通字符精确匹配

 

nginx location 匹配优先级(location在配置文件中的顺序无关)

    1=  精确匹配。如果发现精确匹配,nginx停止搜索其他匹配模式。

   2    普通字符匹配,正则表达式规则和长的块规则将被优先和和查询匹配,也就是说如果该项匹配还需去看有没有正则表达式匹配和更长的匹配

    3^~ 则只匹配该规则,nginx停止搜索其他匹配,nginx停止搜索其他匹配;当没有正则表达式或最后匹配带有"~"

        "~*" 的指令,如果找到相应的匹配,则nginx 停止搜索其他匹配;当没有正则表达式或者没有正则表达式被匹配的情况下,那么匹配程度最高的逐字匹配指令会被使用

location 优先级官方文档

 

   1   Directives with the = prefixthat match the query exactly. If found, searching stops.

   2   All remaining directives withconventional strings, longest match first. If this match used the ^~ prefix,searching stops.

   3    Regular expressions, in orderof definition in the configuration file.

    4If #3 yielded a match, that result is used. Else the match from #2 is used.

 

   1  =前缀的指令严格匹配这个查询。如果找到,停止搜索。

   2  所有剩下的常规字符串,最长的匹配。如果这个匹配使用^前缀,搜索停止。

    3  正则表达式,在配置文件中定义的顺序。

    4  如果第3条规则产生匹配的话,结果被使用。否则,如同从第2条规则被使用。

四 测试location 的优先级顺序

nginx 的配置文件中添加如下内容

   #1

        location ^~ /p_w_picpaths/ {

          rewrite ^/p_w_picpaths/ http://cn.bing.com permanent;

            }

       #2

         location = /p_w_picpaths/ {

          rewrite ^/p_w_picpaths/ http://www.baidu.com/ permanent;

            }

       #3

         location ~* /p_w_picpaths/ {

          rewrite ^/p_w_picpaths/ http://www.ifeng.com/ permanent;

            }

       #4

         location  /p_w_picpaths/frank.html {

          rewrite ^/p_w_picpaths/frank.html http://www.sohu.com/ permanent;

            }

      首先注释掉 #4,并重启nginx,通过浏览器访问:http://192.168.151.78:8866/p_w_picpaths

       location 匹配到的规则为#2,精确匹配,浏览器自动跳转到http://www.baidu.com

     注释掉location 规则#2,重启nginx,并通过浏览器访问http://192.168.151/78:8866/p_w_picpaths

        location 匹配到的规则为#2,普通字符匹配,浏览器自动跳转到http://cn.bing.com

     注释掉location 规则#1,并开启规则location#4,并重启nginx,通过浏览器访问http://192.168.151.78/p_w_picpaths

        location 规则匹配到规则#3,浏览器跳转到http://www.ifeng.com

总结:

    通过上面的测试结果可以看出,nginxlocation

 

 =(精确匹配) > ^~(普通字符匹配) > ~*(正则匹配) > 完全路径

 

               

参考blog:http://www.nginx.cn/115.html