nginx每個location都是一個匹配目錄,nginx的策略是:訪問請求來時,會對訪問地址進行解析,從上到下逐個匹配,匹配上就執行對應location大括號中的策略,並根據策略對請求作出相應。
依訪問地址:http://www.wandouduoduo.com/wddd/index.html為例,nginx配置如下:
location /wddd/ {
proxy_connect_timeout 18000; ##修改成半個小時
proxy_send_timeout 18000;
proxy_read_timeout 18000;
proxy_pass http://127.0.0.1:8080;
}
那訪問時就會匹配這個location,從而把請求代理轉發到本機的8080Tomcat服務中,Tomcat相應后,信息原路返回。總結:location如果沒有“/”時,請求就可以模糊匹配以字符串開頭的所有字符串,而有“/”時,只能精確匹配字符本身。
下面舉個例子說明:
- 配置location /wandou 可以匹配/wandoudouduo請求,也可以匹配/wandou*/duoduo等等,只要以wandou開頭的目錄都可以匹配到。
- 而location /wandou/必須精確匹配/wandou/這個目錄的請求,不能匹配/wandouduoduo/或/wandou*/duoduo等請求。
proxy_pass有無“/”的四種區別探究
訪問地址都是以:http://www.wandouduoduo.com/wddd/index.html 為例。請求都匹配目錄/wddd/
第一種:加"/"
location /wddd/ {
proxy_pass http://127.0.0.1:8080/;
}
測試結果,請求被代理跳轉到:http://127.0.0.1:8080/index.html
第二種: 不加"/"
location /wddd/ {
proxy_pass http://127.0.0.1:8080;
}
測試結果,請求被代理跳轉到:http://127.0.0.1:8080/wddd/index.html
第三種: 增加目錄加"/"
location /wddd/ {
proxy_pass http://127.0.0.1:8080/sun/;
}
測試結果,請求被代理跳轉到:http://127.0.0.1:8080/sun/index.html
第四種:增加目錄不加"/"
location /wddd/ {
proxy_pass http://127.0.0.1:8080/sun;
}
測試結果,請求被代理跳轉到:http://127.0.0.1:8080/sunindex.html
總結
location目錄后加"/",只能匹配目錄,不加“/”不僅可以匹配目錄還對目錄進行模糊匹配。而proxy_pass無論加不加“/”,代理跳轉地址都直接拼接。
server {
listen 80;
server_name localhost; # http://localhost/wddd01/xxx -> http://localhost:8080/wddd01/xxx
location /wddd01/ {
proxy_pass http://localhost:8080;
}
# http://localhost/wddd02/xxx -> http://localhost:8080/xxx
location /wddd02/ {
proxy_pass http://localhost:8080/;
}
# http://localhost/wddd03/xxx -> http://localhost:8080/wddd03*/xxx
location /wddd03 {
proxy_pass http://localhost:8080;
}
# http://localhost/wddd04/xxx -> http://localhost:8080//xxx,請注意這里的雙斜線,好好分析一下。
location /wddd04 {
proxy_pass http://localhost:8080/;
}
# http://localhost/wddd05/xxx -> http://localhost:8080/hahaxxx,請注意這里的haha和xxx之間沒有斜杠,分析一下原因。
location /wddd05/ {
proxy_pass http://localhost:8080/haha;
}
# http://localhost/api6/xxx -> http://localhost:8080/haha/xxx
location /wddd06/ {
proxy_pass http://localhost:8080/haha/;
}
# http://localhost/wddd07/xxx -> http://localhost:8080/haha/xxx
location /wddd07 {
proxy_pass http://localhost:8080/haha;
}
# http://localhost/wddd08/xxx -> http://localhost:8080/haha//xxx,請注意這里的雙斜杠。
location /wddd08 {
proxy_pass http://localhost:8080/haha/;
}
}