location
location 有”定位”的意思,鸣个,根據(jù)Uri來進(jìn)行不同的定位,在虛擬主機(jī)的配置中,是必不可少的吗蚌。
location可以把網(wǎng)站的不同部分,定位到不同的處理方式上腿倚。比如, 碰到.php, 如何調(diào)用PHP解釋器? --這時就需要location
- location 的語法
location [=|~|~*|^~] patt {
}
中括號可以不寫任何參數(shù),此時稱為一般匹配
也可以寫參數(shù),因此,大類型可以分為3種:
location = patt {} [精準(zhǔn)匹配]
location patt{} [一般匹配]
location ~ patt{} [正則匹配]
精準(zhǔn)匹配
- 如何發(fā)揮作用?:
首先看有沒有精準(zhǔn)匹配,如果有,則停止匹配過程.
location = patt {
config A
}
如果 $uri == patt
褪测,匹配成功,使用config A
location =/ {
root www;
index index.htm index.htm;
}
location / {
root html;
index index.html index.htm;
}
上面都是相對路徑潦刃,絕對路徑為usr/local/nginx/www
侮措、/usr/local/nginx/html
如果訪問:http://z.com/
-
定位流程是
- 精準(zhǔn)匹配中
=/
, 根目錄為usr/local/nginx/www
乖杠,得到index頁為index.html
- 再次訪問
/index.html
, 此次內(nèi)部轉(zhuǎn)跳uri已經(jīng)是/index.html
分扎, - 此時一般匹配
/
生效,根目錄為/usr/local/nginx/html
- 最終結(jié)果,訪問了
/usr/local/nginx/html/index.html
- 精準(zhǔn)匹配中
精準(zhǔn)匹配
location =/index.htm {
root www;
index index.htm index.htm;
}
location /index.htm {
root html;
index index.html index.htm;
}
location =/index.htm {
root www;
index index.htm index.htm;
}
location =/ {
root www;
index index.html index.htm;
}
location /index.htm {
root html;
index index.html index.htm;
}
location =/index.html {
root www;
index index.htm index.htm;
}
location =/ {
root www;
index index.html index.htm;
}
location /index.htm {
root html;
index index.html index.htm;
}
正則表達(dá)式
location / {
root html;
index index.html index.htm;
}
location ~ image {
root www;
index index.html index.htm;
}
如果我們訪問 http://z.com/image/logo.png
此時, /
與/image/logo.png
匹配胧洒,同時,image
正則 與image/logo.png
也能匹配,誰發(fā)揮作用?
正則表達(dá)式的成果將會使用畏吓,圖片真正會訪問 /usr/local/www/image/logo.png
location / {
root html;
index index.html index.htm;
}
location /foo {
root www;
index index.html index.htm;
}
我們訪問 http://z.com/foo
對于uri /foo
, 兩個location的patt,都能匹配他們,即 /
能從左前綴匹配 /foo
, /foo
也能左前綴匹配/foo
,
此時, 真正訪問 /usr/local/www/index.html
卫漫,原因:/foo
匹配的更長,因此使用之菲饼;