Nginx中的break和last


rewrite中的break和last

兩個指令用法相同,但含義不同,需要放到rewrite規則的末尾,用來控制重寫后的鏈接是否繼續被nginx配置執行(主要是rewrite、return指令)。

示例1(連續兩條rewrite規則):
server{
    listen 80; 
    server_name test.com;
    root /tmp/123.com;

    rewrite /1.html /2.html ;
    rewrite /2.html /3.html ;
    
}
當我們請求1.html時,最終訪問到的是3.html,兩條rewrite規則先后執行。
break和last在location {}外部
格式:rewrite xxxxx  break;

示例2(增加break):
server{
    listen 80; 
    server_name test.com;
    root /tmp/123.com;

    rewrite /1.html /2.html break;
    rewrite /2.html /3.html;
}
當我們請求1.html時,最終訪問到的是2.html
說明break在此示例中,作用是不再執行break以下的rewrite規則。

但,當配置文件中有location時,它還會去執行location{}段的配置(請求要匹配該location)。

示例3(break后面還有location段):
server{
    listen 80; 
    server_name test.com;
    root /tmp/123.com;

    rewrite /1.html /2.html break;
    rewrite /2.html /3.html;
    location /2.html {
        return 403;
    }
}
當請求1.html時,最終會返回403狀態碼,說明它去匹配了break后面的location{}配置。

以上2個示例中,可以把break替換為last,它們兩者起到的效果一模一樣。
當break和last在location{}里面
示例4(什么都不加):
server{
    listen 80; 
    server_name test.com;
    root /tmp/123.com;
    
    location / {
        rewrite /1.html /2.html;
        rewrite /2.html /3.html;
    }
    location /2.html
    {
        rewrite /2.html /a.html;
    }
    location /3.html
    {
        rewrite /3.html /b.html;
    }
}
當請求/1.html,最終將會訪問/b.html,連續執行location /下的兩次rewrite,跳轉到了/3.html,然后又匹配location /3.html

示例5(增加break):
server{
    listen 80; 
    server_name test.com;
    root /tmp/123.com;
    
    location / {
        rewrite /1.html /2.html break;
        rewrite /2.html /3.html;
    }
    location /2.html
    {
        rewrite /2.html /a.html;
    }
    location /3.html
    {
        rewrite /3.html /b.html;
    }
}
當請求/1.html,最終會訪問/2.html
在location{}內部,遇到break,本location{}內以及后面的所有location{}內的所有指令都不再執行。


示例6(增加last):
server{
    listen 80; 
    server_name test.com;
    root /tmp/123.com;
    
    location / {
        rewrite /1.html /2.html last;
        rewrite /2.html /3.html;
    }
    location /2.html
    {
        rewrite /2.html /a.html;
    }
    location /3.html
    {
        rewrite /3.html /b.html;
    }
}
當請求/1.html,最終會訪問/a.html
在location{}內部,遇到last,本location{}內后續指令不再執行,而重寫后的url再次從頭開始,從頭到尾匹配一遍規則。
結論
  • 當rewrite規則在location{}外,break和last作用一樣,遇到break或last后,其后續的rewrite/return語句不再執行。但后續有location{}的話,還會近一步執行location{}里面的語句,當然前提是請求必須要匹配該location。
  • 當rewrite規則在location{}里,遇到break后,本location{}與其他location{}的所有rewrite/return規則都不再執行。
  • 當rewrite規則在location{}里,遇到last后,本location{}里后續rewrite/return規則不執行,但重寫后的url再次從頭開始執行所有規則,哪個匹配執行哪個。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM