nginx location URL匹配規則

nginx rewrite語法

rewrite regex replacement [flag];

  • regex: 是 PCRE 語法格式的正則表達式,用於匹配字符串。
  • replacement: 是重寫 URI 的改寫規則。當改寫規則以"http://""https://"或"$scheme"開頭時,Nginx 重寫該語句後將停止執行後續任務,並將改寫後的 URI 跳轉返回客戶端。
  • flag: 是執行該條重寫指令後的操作控制符。操作控制符有如下 4 種:
    • break: 執行完當前重寫規則跳轉到新的 URI 後不再執行後續操作。不影響用戶瀏覽器 URI 顯示。
    • last: 執行完當前重寫規則跳轉到新的 URI 後繼續執行後續操作。
    • redirect: 返回響應狀態碼 302 的臨時重定向,返回內容是重定向 URI 的內容,但瀏覽器網址仍爲請求時的 URI;
    • 返回響應狀態碼 301 的永久重定向,返回內容是重定向 URI 的內容,瀏覽器網址變爲重定向的 URI。
      下面一個例子將本地63561代理到nginx代理80端口上,並且所有URL上添加/prefix前綴。
    location /prefix/ {
       rewrite  ^/prefix/(.*)$ /$1 break;
           proxy_pass  http://localhost:63561;          
        }

原來URL http://localhost:63561/aaa => localhost/prefix/aaa
雖然在nginx添加了如下配置,可不一定生效哦,這裏就要講下nginx URI 匹配規則

URI 匹配規則

location Modifier pattern { ... }

Modifier爲location的修飾語,定義URI的匹配規則。pattern 爲匹配項,可以是字符串或正則表達式

  • 沒有修飾符: 從指定模式開始,只支持字符串

location /abc{
root text;
}

下面規則都匹配:
http://localhost/abc/sdssd
http://localhost/abc?page=1&size=10
http://localhost/abcd
http://localhost/abc/

  • =: 完全匹配 URI 中除訪問參數以外的內容,Linux 系統下會區分大小寫,Windows 系統下則不會。

location = /test {
root text;
}

下面都匹配
http://localhost/test
http://localhost/test?page=1&size=10
不匹配
http://localhost/test2ds
http://localhost/test/

  • ~: 區分大小寫的正則匹配

location ~ /abc$ {
root text;
}

下面都匹配
http://localhost/abc
http://localhost/abc?p=123
不匹配
http://localhost/abc/
http://localhost/ABC
http://localhost/abc/bbd

  • ~*: 不區分大小的正則匹配

location ~* /abc$ {
root text;
}

下面都匹配
http://localhost/abc
http://localhsot/ABC
http://localhost/abc?p=123
不匹配
http://localhost/abc/
http://localhost/abc/bbd

  • ^~: 作用類似沒有修飾符的前綴匹配,nginx對一個請求精確前綴匹配成功後,停止繼續搜索其他到匹配項,支持正則表達式。

location ^~ /abc {
root text;
}

  • @: 只能內部訪問的 location 區域,可以被其他內部跳轉指令使用

location @images {
proxy_pass http://images;
}

匹配順序

  1. 先檢測匹配項的內容爲非正則表達式修飾語的 location,然後再檢測匹配項的內容爲正則表達式修飾語的 location。
  2. 匹配項的內容爲正則與非正則都匹配的 location,按照匹配項的內容爲正則匹配的 location 執行。
  3. 所有匹配項的內容均爲非正則表達式的 location,按照匹配項的內容完全匹配的內容長短進行匹配,即匹配內容多的 location 被執行。
  4. 所有匹配項的內容均爲正則表達式的 location,按照書寫的先後順序進行匹配,匹配後就執行,不再做後續檢測。

https://www.w3schools.cn/nginx/nginx_command_localhost.asp

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章