標籤:location
每一個虛擬機器主機或是代理服都需要定義一個location,用以在使用者端查詢時提供搜尋,當匹配到合適的location時,轉向所需的應用。location可以使用正則來查詢匹配,也可以否定匹配,location只針對定義內容進行優先順序匹配,並且在查詢到匹配後忽略其它匹配選項。以下將對可能遇到的一些location進行說明:
-
等於匹配符"=",為精確匹配,不支援正則匹配
-
空匹配符,匹配以指定模式開始的URI,不支援正則匹配
-
正則匹配符"~",這裡包括了三種,以"~"開始的區分大小寫匹配,以"~*"開始的不區分大小寫匹配,以"^~"開始的以指定模式開始的正則匹配
-
內部訪問符"@",一般用於錯誤頁面等
匹配符優先順序
-
=
-
空匹配符,滿足精確匹配時
-
^~
-
~或~*
-
空匹配符
舉例說明upstream tomcats {
server 192.168.100.101:80 max_fails=0 fail_timeout=5s;
server 192.168.100.102:80 max_fails=0 fail_timeout=5s;
}
server {
listen 80;
server_name www.xxx.com;
#1. 空匹配符時,最後生效,與配置先後並無關聯
location / {
proxy_next_upstream http_502 http_504 error timeout invalid_header; proxy_pass http://tomcats;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $remote_addr;
}
#2.實際匹配為"www.xxx.com/showlist/",但優先順序低於"="號
location ~ /showlist {
root /data/html;
index index.html index.htm;
}#3.最先查詢匹配
location = /pages {
root /data/html;
index index.html index.htm;
}
#4.以指定模式進行匹配
location ^~ /file/ {
return 404;
}
#5.等同於"#2"的效果,但匹配內容為以".jpg"結尾的查詢
location ~* \.jpg$ {
root /data/img;
}
#6.在執行動態資源請求時,直接轉向後端伺服器,因為使用了"~*",它優先於第一條規則生效 location ~ .*\.(jsp|do)?$ {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Host $host;
proxy_pass http://tomcats;
proxy_next_upstream http_502 http_504 error timeout invalid_header;
}
#7.精確匹配
location /50x.html {
root /data/html;
}
由以上配置進行測試後可以得出以下匹配優先順序結論:
(location =) > (location 完整路徑 >) >(location ^~ 路徑) >(location ~* 正則) >(location 路徑)
本文出自 “致信” 部落格,請務必保留此出處http://leon0long.blog.51cto.com/3011404/1597217
Nginx代理之location定義