Nginx代理之location定義

來源:互聯網
上載者:User

標籤:location

每一個虛擬機器主機或是代理服都需要定義一個location,用以在使用者端查詢時提供搜尋,當匹配到合適的location時,轉向所需的應用。location可以使用正則來查詢匹配,也可以否定匹配,location只針對定義內容進行優先順序匹配,並且在查詢到匹配後忽略其它匹配選項。以下將對可能遇到的一些location進行說明:

  • location匹配符

  1. 等於匹配符"=",為精確匹配,不支援正則匹配

  2. 空匹配符,匹配以指定模式開始的URI,不支援正則匹配

  3. 正則匹配符"~",這裡包括了三種,以"~"開始的區分大小寫匹配,以"~*"開始的不區分大小寫匹配,以"^~"開始的以指定模式開始的正則匹配

  4. 內部訪問符"@",一般用於錯誤頁面等

匹配符優先順序

  1. =

  2. 空匹配符,滿足精確匹配時

  3. ^~

  4. ~或~*

  5. 空匹配符

舉例說明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定義

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.