理解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

注意,以上的匹配和在配置文件中定義的順序無關。

相關文章
相關標籤/搜索