Nginx做爲一個輕量級的,高性能的web服務軟件,因其佔有內存少,併發能力強的特色,而廣受歡迎和使用。國內不少大型互聯網公司也對Nginx非常青睞。像BAT(百度,阿里和騰訊),TMD(頭條,美團和滴滴)等等。使用過Nginx的同窗都知道,你只須要按需求準確的更改好配置啓動,那麼就能夠優雅的訪問它了。因此說Nginx對配置文件的非常看中呢,這就要求咱們更改配置文件時必定要再三確認,要否則可能由於疏忽而引起慘案呢?html
真實案例,就由於在配置時,少些了一個字符「/」,就形成訪問不通報錯,於是接到投訴。那麼是怎麼引發的呢?緣由就是:Nginx在配置proxy_pass代理轉接時,少些「/」字符形成的。nginx
有同窗就有疑問,加不加「/」,區別真的那麼大嗎?咱們帶着這個疑問,來探究下這個問題。location目錄匹配詳解web
nginx每一個location都是一個匹配目錄,nginx的策略是:訪問請求來時,會對訪問地址進行解析,從上到下逐個匹配,匹配上就執行對應location大括號中的策略,並根據策略對請求做出相應。api
以訪問地址:http://www.wandouduoduo.com/w...,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等請求。spa
proxy_pass有無「/」的四種區別探究設計
訪問地址都是以:http://www.wandouduoduo.com/w... 爲例。請求都匹配目錄/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/; } }
看到這裏,是否是以爲有點區別呢??每一種配置都有它不一樣的意義與區別。太讚了!牆裂推薦這款網頁版 Nginx 配置生成器,好用到爆!
若是本文對你有所幫助,請點個在看與轉發分享支持一波。