「Nginx」02節-Nginx location 匹配規則詳解

Nginx 中主要通過location來匹配請求規則,它也是區分匹配優先級的,但很多同學對此比較迷糊,本節就來詳細介紹一下Nginx location的規則。

Nginx location 語法規則

location [=|~|~*|^~] /uri/ {
....
}

Nginx location 模式說明

「Nginx」02節-Nginx location 匹配規則詳解

Nginx location 模式含義

乍一看是不是有點似懂非懂的感覺?沒關係,我們來舉例詳細說明一下,加深印象與理解。

# 精確匹配URL為 /abc 的請求
location = /abc {
....
}

http://xxx.com/abc 可以訪問;

http://xxx.com/abc?args=123 可以訪問;

http://xxx.com/abc/ 報404錯誤;

http://xxx.com/abc/def 報404錯誤;

# 精確匹配URL為 /abc/ 的請求
location = /abc/ {
....
}

http://xxx.com/abc 報404錯誤;

http://xxx.com/abc?args=123 報404錯誤;

http://xxx.com/abc/ 可以訪問;

http://xxx.com/abc/?args=123 可以訪問;

http://xxx.com/abc/def 報404錯誤;

# 匹配URL以 /abc 開頭的請求(在正則匹配之前)
location ^~ /abc {
....
}

http://xxx.com/abc 可以訪問;

http://xxx.com/abc/def 可以訪問;

# 正則匹配URL以 /efg 開頭的請求,且URL區分大小寫
location ~ /abc {
....
}

http://xxx.com/efg 可以訪問;

http://xxx.com/efG 報404錯誤;

# 正則匹配URL以 /efg 開頭的請求,且URL不區分大小寫
location ~* /abc {
....
}

http://xxx.com/efg 可以訪問;

http://xxx.com/efG 可以訪問;

Nginx location 匹配優先級

  • 首先精確匹配 =
  • 其次前綴匹配 ^~
  • 其它按location定義的順序進行正則相關匹配
  • 然後匹配不帶任何修飾的前綴匹配
  • 以上都匹配不到時,交給 / 通用匹配

當有規則與之匹配時,就會按當前規則進行處理,並停止匹配了。

好了,到此就講解完畢了,網絡圈只撿重要的講,其實還有一些小細節等大家遇到再去查資料,否則很容易把自己弄暈。

如果覺得本節有收穫,大家可以關注支持一下我哦 ~


分享到:


相關文章: