理解NGINX的重写break和last,以及location匹配规

理解NGINX的重写break和last,以及location匹配规则

2018年05月05日 23:37:41 Lan的CSDN 阅读数:197php

        location / {
            index  index.html index.htm index.php l.php;
if (!-e $request_filename) {
rewrite /[ac]\d+\.html /index/index/home last;
rewrite ^/admin$ /admin/login/login last;
rewrite ^(.*)$ /index.php?s=$1 last;
break;

}
           autoindex  off;html

        }nginx

1.break在重写语句后会中止后续的重写规则:rewrite ^(.*)$ /index.php?s=$1 break; 包括其余的location均不会再执行匹配正则表达式

2.单独写:rewrite ^(.*)$ /index.php?s=$1 last;
break;url

 

 

 

 

  只会中止本location的重写规则。会用重写后的url执行其余的locationspa

3.last会用重写后的url从新匹配全部的重写规则。包括本location里面的,意思为整个server里面的从新匹配。.net

4.注意:很是须要注意的是,重写规则会先匹配location外层的 如location =/1.php{rewrite ^(.*)$ /2.php last; , location ~ \.php(.*)$ ,location /flag { rewrite ^(.*)$ /1.php last; 。三种规则。访问http://localhost/flag/1.php并不会访问到2.phpcode

而是出现:No input file specified.  由于 已经匹配到了location ~ \.php(.*)$规则。因为没有/flag/1.php因此出现找不到文件。server

因此想要访问/flag/1.php获得 2.php的内容的话:修改location /flag { rewrite ^(.*)$ /1.php last 为 location ^~ /flag { rewrite ^(.*)$ /1.php lasthtm

5.nginx location的url 匹配优先级:

            一、=  首先是精准匹配优先级最高

            二、^~ 其次是以某特定常规字符串开头的匹配,这个不是正则

            三、~ 、 ~*、!~、!~* 再次是按顺序的正则匹配,依次为区分大小写的正则匹配、不区分大小写的正则匹配、依次为区分大小写的正则不匹配、不区分大小写的正则不匹配、

            四、最后是 / 的通用符匹配

            以上依次为nginx location的url 匹配优先级

 

location优先级示例

配置项以下:

 
  1. location = / {
  2. # 仅仅匹配请求 /
  3. [ configuration A ]
  4. }
  5. location / {
  6. # 匹配全部以 / 开头的请求。
  7. # 可是若是有更长的同类型的表达式,则选择更长的表达式。
  8. # 若是有正则表达式能够匹配,则优先匹配正则表达式。
  9. [ configuration B ]
  10. }
  11. location /documents/ {
  12. # 匹配全部以 /documents/ 开头的请求。
  13. # 可是若是有更长的同类型的表达式,则选择更长的表达式。
  14. # 若是有正则表达式能够匹配,则优先匹配正则表达式。
  15. [ configuration C ]
  16. }
  17. location ^~ /images/ {
  18. # 匹配全部以 /images/ 开头的表达式,若是匹配成功,则中止匹配查找。
  19. # 因此,即使有符合的正则表达式location,也不会被使用
  20. [ configuration D ]
  21. }
  22. location ~* \.(gif|jpg|jpeg)$ {
  23. # 匹配全部以 gif jpg jpeg结尾的请求。
  24. # 可是 以 /images/开头的请求,将使用 Configuration D
  25. [ configuration E ]
  26. }

请求匹配示例

 
  1. / -> configuration A
  2. /index.html -> configuration B
  3. /documents/document.html -> configuration C
  4. /images/1.gif -> configuration D
  5. /documents/1.jpg -> configuration E

注意,以上的匹配和在配置文件中定义的顺序无关。

相关文章
相关标签/搜索