location /test/break { # break測試 location1 rewrite ^.*/test(.*)$ "/here" break; } location /test/last { # last測試 location2 rewrite ^.*/test(.*)$ "/here" last; } location /here { # 正常地址 location3 default_type text/html; return 200 "<h1>ok</h1>"; }
1.首先測試下break, 請求/test/break,結果以下圖html
請求/test/break 匹配到location1,而後地址重寫爲/here,返回404,表示沒有再次匹配location
nginx
2.測試last, 請求/test/last,結果以下圖json
請求/test/break 匹配到location2,而後地址重寫爲/here,正常返回ok頁面,表示重寫後又再次匹配全部location
api
break表示重寫後中止再也不匹配,last表示重寫後跳到server塊再次用重寫後的地址匹配
跨域
1.break
通常用於接口重定向,例如將http://127.0.0.1/down/123.xls...://192.168.0.1:8080/file/123.xls(解決跨域下載)測試
location /down { rewrite ^/down(.*)$ "http://192.168.0.1:8080/file$1" break; }
2.last
用於請求路徑發生改變的常規需求,例如將http://127.0.0.1/request/getlist 放在了對應 http://127.0.0.1/api/getlistspa
location /request { rewrite ^/request(.*)$ "/api" last; } location /api { default_type Application/json; return 200 '{"code":0,data:[1,2,3]}'; }