1. 程式人生 > >Nginx得Location配置詳解之精準匹配

Nginx得Location配置詳解之精準匹配

location的匹配過程

一、location 的定義

location 有“定位”的意思,根據Uri來進行不同的定位。

在虛擬主機的配置中,是必不可少得,location可以把網站的不同部分,定位到不同的處理方式上。

二、location 的語法

location [=|~|~*|^~] patt{


}

中括號可以不寫任何參數,此時稱為一般匹配,也可以寫參數

因此,大類新可以分為3種:

location=patt{}[精準匹配]

location patt{} [一般匹配]

location ~patt{}[正則匹配]

1、如何發揮作用?

首先看有沒有精準匹配,如果有,則停止匹配過程。

location=patt{

config A

}

如果$uri==patt,匹配成功,使用configA

location =/ {

root /var/www/html;

index index.htm index.html;

}


location / {

root html;

index index.html index.htm;

}

如果訪問 http://xxx.com/

定位流程是:

1.精準匹配中 “/”,得到index頁為 index.htm

2.再次訪問 /index.htm,此次內部跳轉uri已經是“/index.htm”

根目錄為/usr/local/nginx/html

3.最終結果,訪問了 /usr/local/nginx/html/index.htm


2.正則表達式匹配:

location / {

root html;

index index.html index.htm;

}



location ~ image{

root /var/www/image;

index index.html;

}

如果訪問 http://xx.com/image/logo.png

此時,“/”與“/image/logo.png”匹配

同時,“/image”正則與“image/logo.png”也能匹配,誰發揮作用?

正則表達式的成功將被使用


圖片真正會訪問 /var/www/image/logo.png




location / {

root /usr/local/nginx/html;

index index.html index.htm;

}


location /foo {

root /var/www/html;

index index.html;

}

此時我們訪問 xxx.com/foo

對於uri “/foo”,兩個location的patt都能匹配他們

既“/”能從左前綴匹配“/foo”,“/foo”也能左前綴匹配“/foo”,

此時,真正訪問 /var/www/html/index.html

原因:“/foo”匹配的更長,因此使用之。


三、總結:

location 匹配流程圖:

技術分享圖片

location的命中過程是這樣的:

1.先判斷精準命中,如果命中,立即返回結果並結束解析過程。

2.判斷普通命中,如果有多個命中,記錄下來最長的命中結果,(註意:記錄但不結束,最長的為準)

3.繼續判斷正則表達式的解析結果,按配置裏的正則表達式順序為準,由上到下開始匹配,一旦匹配成功1個,立即返回結果,並結束解析過程。


延伸分析:

1、普通命中,順序無所謂,是因為按命中的長短來確定的。

2、正則命中,順序有所謂,因為是從前往後命中的。

Nginx得Location配置詳解之精準匹配