總結: rewrite 能夠在 server location 塊, 正則比配的時候才重寫,因此多條 rewrite 順序靠前且匹配的優先執行。php
break跳出rewrite階段,不會在匹配,進入輸出階段。 last 相似從新發起請求,因此會從新進行匹配。html
轉自:http://blog.sina.com.cn/s/blog_4f9fc6e10102ux0w.htmlnginx
http://blog.cafeneko.info/2010/10/nginx_rewrite_note/ 或者 http://yuanhsh.iteye.com/blog/1321982spa
nginx 的官方註釋是這樣的:server
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;
咱們知道nginx運行分十一個執行階段,上面說提到的ngx_http_rewrite_mode,能夠理解爲其中一個階段-rewrite階段。htm
typedef enum { NGX_HTTP_POST_READ_PHASE = 0, NGX_HTTP_SERVER_REWRITE_PHASE, NGX_HTTP_FIND_CONFIG_PHASE, NGX_HTTP_REWRITE_PHASE, //rewrite階段在這裏 NGX_HTTP_POST_REWRITE_PHASE, NGX_HTTP_PREACCESS_PHASE, NGX_HTTP_ACCESS_PHASE, NGX_HTTP_POST_ACCESS_PHASE, NGX_HTTP_TRY_FILES_PHASE, NGX_HTTP_CONTENT_PHASE, NGX_HTTP_LOG_PHASE } ngx_http_phases;
因此咱們再來理解last與break的區別:
last: 中止當前這個請求,並根據rewrite匹配的規則從新發起一個請求。新請求又從第一階段開始執行…
break:相對last,break並不會從新發起一個請求,只是跳過當前的rewrite階段,並執行本請求後續的執行階段…blog
咱們來看一個例子:it
server { listen 80 default_server; server_name dcshi.com; root www; location /break/ { rewrite ^/break/(.*) /test/$1 break; echo "break page"; } location /last/ { rewrite ^/last/(.*) /test/$1 last; echo "last page"; } location /test/ { echo "test page"; } }
請求:http://dcshi.com/break/***
輸出: break page
分析:正如上面討論所說,break是跳過當前請求的rewrite階段,並繼續執行本請求的其餘階段,很明顯,對於/foo 對應的content階段的輸出爲 echo 「break page」; (content階段,能夠簡單理解爲產生數據輸出的階段,如返回靜態頁面內容也是在content階段;echo指令也是運行在content階段,通常狀況下content階段只能對應一個輸出指令,如同一個location配置兩個echo,最終只會有一個echo指令被執行);固然若是你把/break/裏的echo 指令註釋,而後再次訪問/break/xx會報404,這也跟咱們預期同樣:雖然/break/xx被重定向到/test/xx,可是break指令不會從新開啓一個新的請求繼續匹配,因此nginx是不會匹配到下面的/test/這個location;在echo指令被註釋的狀況下,/break/ 這location裏只能執行nginx默認的content指令,即嘗試找/test/xx這個html頁面並輸出起內容,事實上,這個頁面不存在,因此會報404的錯誤。io
請求: http://dcshi.com/last/***
輸出: test page
分析: last與break最大的不一樣是,last會從新發起一個新請求,並從新匹配location,因此對於/last,從新匹配請求之後會匹配到/test/,因此最終對應的content階段的輸出是test page;ast
假設你對nginx的運行階段有一個大概的理解,對理解last與break就沒有問題了。
location ~ ^/testtest/ {
default_type text/html;
echo 111;
}
rewrite ^/testtest/ /test.php last;
訪問 /testtest/的時候,輸出的值是/test.php的內容,顯然,重寫到rewrite上了,交換rewrite和location位置,執行結果不變,說明這個和位置無關。