nginx配置檔案中字元"/"加與不加的區別
location目錄匹配詳解
nginx每個location都是一個匹配目錄,nginx的策略是:訪問請求來時,會對訪問地址進行解析,從上到下逐個匹配,匹配上就執行對應location大括號中的策略,並根據策略對請求作出相應。
依訪問地址:http://www.wandouduoduo.com/wddd/index.html為例,nginx配置如下:
1 location /wddd/ { 2 proxy_connect_timeout 18000; ##修改成半個小時 3 proxy_send_timeout 18000; 4 proxy_read_timeout 18000; 5 proxy_pass http://127.0.0.1:8080;6 }
那訪問時就會匹配這個location,從而把請求代理轉發到本機的8080埠的Tomcat服務中,Tomcat響應後,資訊原路返回。總結:location如果沒有“/”時,請求就可以模糊匹配以字串開頭的所有字串,而有“/”時,只能精確匹配字元本身。
下面舉個例子說明:
配置 location /wandou 可以匹配 /wandoudouduo 請求,也可以匹配 /wandou*/duoduo 等等,只要以 wandou 開頭的目錄都可以匹配到。而 location /wandou/ 必須精確匹配 /wandou/ 這個目錄的請求, 不能匹配 /wandouduoduo/ 或 /wandou*/duoduo 等請求。
proxy_pass有無“/”的四種區別探究
訪問地址都是以:http://www.wandouduoduo.com/wddd/index.html 為例。請求都匹配目錄/wddd/
第一種:加"/"
1 location /wddd/ { 2 proxy_pass http://127.0.0.1:8080/; 3 }
測試結果,請求被代理跳轉到:http://127.0.0.1:8080/index.html
第二種: 不加"/"
1 location /wddd/ { 2 proxy_pass http://127.0.0.1:8080; 3 }
測試結果,請求被代理跳轉到:http://127.0.0.1:8080/wddd/index.html
第三種: 增加目錄加"/"
1 location /wddd/ { 2 proxy_pass http://127.0.0.1:8080/sun/; 3 }
測試結果,請求被代理跳轉到:http://127.0.0.1:8080/sun/index.html
第四種:增加目錄不加"/"
1 location /wddd/ { 2 proxy_pass http://127.0.0.1:8080/sun; 3 }
測試結果,請求被代理跳轉到:http://127.0.0.1:8080/sunindex.html
總結
location目錄後加 "/", 只能匹配目錄,不加 “/” 不僅可以匹配目錄還對目錄進行模糊匹配。而proxy_pass無論加不加“/”,代理跳轉地址都直接拼接。
為了加深大家印象可以用下面的配置實驗測試下:
1 server { 2 listen 80; 3 server_name localhost; 4 5 # http://localhost/wddd01/xxx -> http://localhost:8080/wddd01/xxx 6 location /wddd01/ { 7 proxy_pass http://localhost:8080; 8 } 9 10 # http://localhost/wddd02/xxx -> http://localhost:8080/xxx 11 location /wddd02/ { 12 proxy_pass http://localhost:8080/; 13 } 14 15 # http://localhost/wddd03/xxx -> http://localhost:8080/wddd03*/xxx 16 location /wddd03 { 17 proxy_pass http://localhost:8080; 18 } 19 20 # http://localhost/wddd04/xxx -> http://localhost:8080//xxx,請注意這裡的雙斜線,好好分析一下。 21 location /wddd04 { 22 proxy_pass http://localhost:8080/; 23 } 24 25 # http://localhost/wddd05/xxx -> http://localhost:8080/hahaxxx,請注意這裡的haha和xxx之間沒有斜槓,分析一下原因。 26 location /wddd05/ { 27 proxy_pass http://localhost:8080/haha; 28 } 29 30 # http://localhost/api6/xxx -> http://localhost:8080/haha/xxx 31 location /wddd06/ { 32 proxy_pass http://localhost:8080/haha/; 33 } 34 35 # http://localhost/wddd07/xxx -> http://localhost:8080/haha/xxx 36 location /wddd07 { 37 proxy_pass http://localhost:8080/haha; 38 } 39 40 # http://localhost/wddd08/xxx -> http://localhost:8080/haha//xxx,請注意這裡的雙斜槓。 41 location /wddd08 { 42 proxy_pass http://localhost:8080/haha/; 43 } 44 }
參考原文CSDN博主「戴國進」 https://blog.csdn.net/JineD/article/details/121102344