Nginx Rewrite規則的break和last示例


break和last各自的作用

官方解釋
last:stops processing the current set of ngx_http_rewrite_module directives followed by a search for a new location matching the changed URI;
break:stops processing the current set of ngx_http_rewrite_module directives;
last: 停止當前這個請求,匹配成功后會跳出本條location,會執行其他location,會並根據rewrite匹配的規則重新發起一個請求。
break:相對last,break並不會重新發起一個請求,跳出所有location, 其他location也都不會去執行了,只是跳過當前的rewrite階段,並執行本請求后續的執行階段,比如在匹配成功后訪問指定的目錄文件

舉例說明
last情況

server {
    listen 80;
    server_name wqy.test.com;
    access_log logs/wqy-test-com/access.log;
    location ^~ /aaa {
        rewrite ^/aaa/(.*) /bbb/$1 last;
        root /opt/tmp/wqy/test;
    }
    location ^~ /bbb {
        return 200 "hello world\n";
    }
}

測試

#curl -s http://wqy.test.com/aaa/index.html -x 127.0.0.1:80
hello world
#curl -s http://wqy.test.com/bbb/index.html -x 127.0.0.1:80
hello world

重點說明
當訪問域名wqy.test.com/aaa的時候,后面跟的是/bbb/$1,再往后走發現是last規則,就停止當前規則,跳出loaction再重新執行location匹配一遍,這個時候的域名變成wqy.test.com/bbb/,重新匹配到/bbb,然后返回hello world
當訪問域名wqy.test.com/bbb的時候,后面跟的是直接匹配的/bbb然后返回hello world

break情況

server {
    listen 80;
    server_name wqy.test.com;
    access_log logs/wqy-test-com/access.log;
    location ^~ /aaa {
        rewrite ^/aaa/(.*) /bbb/$1 break;
        root /opt/tmp/wqy/test;
    }
    location ^~ /bbb {
        return 200 "hello world\n";
    }
}

測試

#curl -s http://wqy.test.com/aaa/index.html -x 127.0.0.1:80
bbb
#curl -s http://wqy.test.com/bbb/index.html -x 127.0.0.1:80
hello world

重點說明
當訪問域名wqy.test.com/aaa的時候,后面跟的是/bbb/$1,再往后走發現是break規則,不在跳出location直接就是匹配成功,讀取root /opt/tmp/wqy/test/bbb文件內容bbb
當訪問域名wqy.test.com/bbb的時候,后面跟的是直接匹配的/bbb然后返回hello world

如果以上還是不明白那么看下面這個例子

location /break/ {
		rewrite ^/break/(.*) /test/$1 break;
		return 402;
}
location /last/ {
		rewrite ^/last/(.*) /test/$1 last;
		return 403;
}
location /test/ {
		return 508;
}

請求break:如果請求開頭為/break/index.html 因為后面是break,不再進行重新匹配,就直接訪問/test下的index.html文件內容,如果/test下沒有文件就返回404找不到報錯
請求last:如果是請求開頭為/last/index.html,因為后面是last,重新跳出本location進行匹配,/test/ 直接返回508(訪問last相當於直接訪問/test/)


免責聲明!

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



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