前面我們一起學習了location的匹配規則,如果還不瞭解的話可以參考我這邊文章(nginx中location的使用),今天一起來學習nginx中proxy_pass的匹配過程,也是非常簡單
proxy_pass匹配主要分兩種情況
1、proxy_pass代理的url後面只有ip(域名)+端口,其他什麼都沒有(包括"/"都不能有)
此時代理的路徑需要把請求的url中ip+port後面的路徑追加到proxy_pass後面
例如:
假設http的請求路徑爲:http://120.24.95.148:9998/nginx/hello?name=taolong
nginx配置文件內容
server {
listen 9998;
server_name 120.24.95.148;
#匹配規則
location /nginx {
proxy_pass http://120.24.95.148:10010;
}
}
此時
proxy_pass後面的url=http://120.24.95.148:10010,沒有任何內容
這是就需要將http請求路徑中的 “nginx/hello?name=taolong”內容追加到proxy_pass的url後面
最終代理的路徑爲:http://120.24.95.148:10010/nginx/hello?name=taolong
2、proxy_pass代理的url後面除了ip(域名)+端口,還有其他的內容
此時的匹配邏輯,就需要將請求中的未匹配到location的內容追加到proxy_pass的url後面
例如:
假設http的請求路徑爲:http://120.24.95.148:9998/nginx/hello?name=taolong
nginx配置文件的內容如下:
server {
listen 9998;
server_name 120.24.95.148;
#匹配規則
location /nginx/hello {
#注意這裏是“/”結尾,請求url中未匹配的內容:?name=taolong
proxy_pass http://120.24.95.148:10010/hello;
}
#此時上面輸出的結果:http://120.24.95.148:10010/hello?name=taolong
#匹配規則
location /nginx {
#注意這裏是“/”結尾,請求url中未匹配的內容:/hello?name=taolong
proxy_pass http://120.24.95.148:10010/;
}
#此時上面輸出的結果:http://120.24.95.148:10010/hello?name=taolong
}
proxy_pass就到上面就結束了,下面順帶提一下nginx還有一種類似上面的情況,就是root和alias的使用
root和alias使用
當使用root時,就類似上面第一種情況,直接對應到root指定的目錄
當使用alias時,就類似上面的第二種情況,將爲匹配的內容追加到alias的url後面
#測試路徑:/root
#定位的內容:/etc/nginx/html/root/a.html;
location /root {
root /etc/nginx/html;
index a.html;
}
#測試路徑:/root/test
#定位的內容:/etc/nginx/html/root/test/b.html;
location /root/test {
root /etc/nginx/html;
index a.html;
}
#測試路徑:/alias/test/a
#定位的內容:/etc/nginx/html/test/a/b.html
location /alias {
alias /etc/nginx/html;
index b.html;
}
#測試路徑:/alias/test/
#定位的內容:/etc/nginx/html/a.html
location /alias/test {
alias /etc/nginx/html;
index a.html;
}
· #正則$1表示第一次匹配的路徑變量對應匹配的.*的內容
#測試路徑/aliasregex/test ---》定位的內容/etc/nginx/html/test/a.html
#測試路徑/aliasregex/a ---》定位的內容/etc/nginx/html/a/a.html
location ~ /aliasregex/(.*) {
alias /etc/nginx/html/$1;
index a.html;
}