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.pnghtml

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

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

請求/test/break 匹配到location2,而後地址重寫爲/here,正常返回ok頁面,表示重寫後又再次匹配全部locationapi

總結

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]}';
}
相關文章
相關標籤/搜索