1、語法
location [=|~|~*|^~|@] /uri/ { ...}
2、說明
從上面的語法出發,可以了解到 location 可以區分為三個部分,接下來一個一個的研究一下。
1) [=|~|~*|^~|@]
= : 表示精確匹配后面的url ~ : 表示正則匹配,但是區分大小寫 ~* : 正則匹配,不區分大小寫 ^~ : 表示普通字符匹配,如果該選項匹配,只匹配該選項,不匹配別的選項,一般用來匹配目錄 @ : "@" 定義一個命名的 location,使用在內部定向時,例如 error_page上面定義了幾個不同的符號,表示不同的匹配規則,那么先后順序呢?
測試示例1:
location = /world { return 600;}location = /hello { return 600;}location ~ /hellowo { return 602;}location ^~ /hello { return 601;}
- 請求 localhost/world 返回600- 請求 localhost/world2 localhost/test/world 返回其他- 請求 localhost/hello 返回600- 請求 localhost/hello/123 返回601- 請求 localhost/hellow 返回601- 請求 localhost/hellowo 返回601- 請求 localhost/test/hellowo 返回602- 請求 localhost/test/hello 返回其他
因此可以知道:
= 是精確完整匹配,且優先級最高; 正則匹配時,如果 ~ 和 ^~ 同時匹配規則,則 ^~ 優先; ^~ 這個規則不會匹配請求 url 中后面的路徑,如上面的 /test/hello 沒有匹配上 ^~ 不支持正則,和 = 相比,范圍更廣,hellowo 是可以被 ^~ 匹配,但是 = 不會匹配; ~ 路徑中只要包含就可以匹配,如上面的 /test/hellowo 返回了 602測試示例2:
location ~ /hello { return 602;}location ~ /helloworld { return 601;}
- 請求 localhost/world/helloworld 返回 602- 請求 localhost/helloworld 返回 602
調整上面的順序
location ~ /helloworld { return 601;}location ~ /hello { return 602;}
- 請求 localhost/helloworld 返回601- 請求 localhost/world/helloworld 返回601- 請求 localhost/helloWorld 返回602
所以同時正則匹配時
放在前面的優先匹配 注意如果不區分大小寫時,使用 ~* 盡量將精確匹配的放在前面測試示例3:
location ^~ /hello/ { return 601;}location /hello/world { return 602;}
這種場景中,存在一個沒有符合的路由規則,那么實際的測試是怎樣呢?
- http://localhost/hello/wor 返回601- http://localhost/hello/world 返回602- http://localhost/hello/world23 返回602- http://localhost/hello/world/123 返回602
新聞熱點
疑難解答