Nginx實踐:(2) Nginx語法之localtion
1. 概念
location是根據uri進行不同的定位。在虛擬主機的配置中,是必不可少的。location可以將網站的不同部分,定位到不同的處理方式上。
location語法格式如下:
location [=|~|~*|^~] patt{
}
其中:
(1) 當[]中的內容均不填寫時,表示一般匹配
(2) "="表示精準匹配
(3) "~"表示正則匹配
2. 精確匹配
當uri匹配時,首先檢測是否存在精準匹配,如果存在,則停止匹配過程。
例1:
// 如果$uri==patt,則匹配成功,使用config A location = patt { config A }
例2:
location = / { root/var/www/html/; index index.htm index.html; } location / { root /usr/local/nginx/html; index index.html index.htm; }
如果訪問http://ip:port/,則其定位流程是:a) 精準匹配" = /",得到index頁為index.htm; b) 再次訪問/index.htm,此次內部跳轉已經是"/index.htm"(一般匹配),其根目錄為/usr/local/nginx/html; c) 最終結果,訪問了/usr/local/nginx/html/index.htm。
3. 正則匹配
location / { root /usr/local/nginx/html; index index.html index.htm; } location~ image { root /var/www/; index index.html; }
假設服務器存在/usr/local/nginx/html/image/1.jpg路徑,當我們訪問http://xx.com/image/1.jpg時,此時"/"與"/image/1,jpg"匹配,同時 "image"正則與"image/1.jpg"也能夠匹配,二者誰會發揮作用?答案是二者均會起作用,但是最終起作用的是正則表達式,正則表達式會將之前匹配的覆蓋掉,因此圖片真正訪問/var/www/image/1.jpg。
4. 一般匹配
location /{ root /usr/local/nginx/html; index index.html index.htm; } location/foo { root /var/www/html/; index index.html; }
當訪問http://xxx.com/foo時,對於uri "/foo",兩個location的patt都能匹配他們。即"/"能從左前綴匹配‘/foo‘,‘/foo‘也能左前綴匹配‘/foo‘,此時真正訪問的是‘/var/www/html/index.html‘,原因是‘/foo‘匹配的更長,優先進行匹配。
5. location命中匹配過程
(1) 首先判斷精準命中,如果命中,立即返回結果並結束解析過程
(2) 判斷普通命中,如果有多個命中,"記錄"下來"最長"的命中結果(註意:記錄但不結束,最長的為準)
(3) 繼續判斷正則表達式的解析結果,按配置中的正則表達式順序為準,由上到下開始匹配,一旦匹配成功一個,立即返回結果,並結束解析過程
延伸分析:a: 普通命中順序無所謂,是因為按命中的長短來確定的 b: 正則命中,順序有所謂,是因為從前往後命中的
Nginx實踐:(2) Nginx語法之localtion