nginx rewrite的break於last區別

nginx rewrite的break於last區別

示例nginx配置

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,結果如下圖
QQ截圖20191021143157.png

請求/test/break 匹配到location1,然後地址重寫爲/here,返回404,表示沒有再次匹配location

2.測試last, 請求/test/last,結果如下圖
QQ截圖20191021143221.png

請求/test/break 匹配到location2,然後地址重寫爲/here,正常返回ok頁面,表示重寫後又再次匹配所有location

總結

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/getlist

location /request {
  rewrite ^/request(.*)$ "/api" last;
}

location /api {
  default_type Application/json;
  return 200 '{"code":0,data:[1,2,3]}';
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章