背景: Nginx 中想在 一個(gè)location 中通過(guò)root 指令單獨(dú)定義一個(gè)linux 系統(tǒng)下的目錄當(dāng)作此location 讀取資源的目錄敷钾。
以下測(cè)試場(chǎng)景發(fā)起請(qǐng)求的url : http://192.168.8.198:19999
遇到的坑: 當(dāng)我在location 中用精確匹配(=) 進(jìn)行匹配在同一個(gè)location 中使用root 指令指定資源目錄時(shí), 此時(shí)nginx會(huì)讀取 它的默認(rèn)資源目錄(nginx/html),無(wú)法達(dá)請(qǐng)求到我所指定目錄下資源众羡。
#代碼示例
server{
listen 19999 ;
server_name www.test.com;
#root /html/www/;
error_log /nginx/logs/test.log;
access_log /nginx/logs/test.log;
location = / {
root /html/www/;
index index.html;
}
}
經(jīng)過(guò)測(cè)試驗(yàn)證,總結(jié)以下規(guī)律:
經(jīng)過(guò)測(cè)試發(fā)現(xiàn) alias 指令和root指令此場(chǎng)景使用效果相同
-
在location 中使用精確匹配時(shí),通過(guò)root 指令 在http、或server 中指定資源目錄(/html/www/)就可以被讀取到鲫售。
#代碼示例 server{ listen 19999 ; server_name www.test.com; root /html/www/; error_log /nginx/logs/test.log; access_log /nginx/logs/test.log; location = / { index index.html; } }
-
在location 中 使用^~秦效、 ~ 法梯、 ~*、/等匹配方式夜惭,姻灶,通過(guò)root 指令指定資源目錄(/html/www/) 也可以被正常讀取到。
#代碼示例 server{ listen 19999 ; server_name www.test.com; error_log /nginx/logs/test.log; access_log /nginx/logs/test.log; location ~ / { root /html/www/; index index.html; } }
驗(yàn)證上一個(gè)場(chǎng)景的過(guò)程中诈茧,總結(jié) root指令 和 alias 指令 使用的一些區(qū)別
若用alias的話产喉,則訪問(wèn)/img/目錄里面的文件時(shí),ningx會(huì)自動(dòng)去/var/www/image/目錄找文件敢会,比如:
發(fā)起請(qǐng)求 http://192.168.8.198:19999/local
則是對(duì)應(yīng)到服務(wù)器下的/html/www/index.html
, 說(shuō)明 在使用alias 指令時(shí)曾沈,location 處的 匹配只做請(qǐng)求的匹配驗(yàn)證,請(qǐng)求帶的uri 不會(huì)更改alias 指定的資源目錄走触。
location /local {
alias /html/www/;
index index.html;
}
若用root的話晦譬,則訪問(wèn)/img/目錄下的文件時(shí),nginx會(huì)去/var/www/image/img/目錄下找文件 ,比如:
發(fā)起請(qǐng)求http://192.168.8.198:19999/www
則是對(duì)應(yīng)服務(wù)器下的/html/www/index.html
互广,說(shuō)明 請(qǐng)求帶的uri 中的路徑會(huì)自動(dòng)拼接到root指定的資源目錄后邊敛腌。
location /www {
root /html/;
index index.html;
}