背景: Nginx 中想在 一個(gè)location 中通過root 指令單獨(dú)定義一個(gè)linux 系統(tǒng)下的目錄當(dāng)作此location 讀取資源的目錄。
以下測試場景發(fā)起請求的url : http://192.168.8.198:19999
遇到的坑: 當(dāng)我在location 中用精確匹配(=) 進(jìn)行匹配在同一個(gè)location 中使用root 指令指定資源目錄時(shí), 此時(shí)nginx會讀取 它的默認(rèn)資源目錄(nginx/html),無法達(dá)請求到我所指定目錄下資源。
#代碼示例
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)過測試驗(yàn)證,總結(jié)以下規(guī)律:
經(jīng)過測試發(fā)現(xiàn) alias 指令和root指令此場景使用效果相同
-
在location 中使用精確匹配時(shí),通過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 中 使用^~、 ~ 、 ~*、/等匹配方式,,通過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è)場景的過程中,總結(jié) root指令 和 alias 指令 使用的一些區(qū)別
若用alias的話,則訪問/img/目錄里面的文件時(shí),ningx會自動去/var/www/image/目錄找文件,比如:
發(fā)起請求 http://192.168.8.198:19999/local 則是對應(yīng)到服務(wù)器下的/html/www/index.html, 說明 在使用alias 指令時(shí),location 處的 匹配只做請求的匹配驗(yàn)證,請求帶的uri 不會更改alias 指定的資源目錄。
location /local {
alias /html/www/;
index index.html;
}
若用root的話,則訪問/img/目錄下的文件時(shí),nginx會去/var/www/image/img/目錄下找文件 ,比如:
發(fā)起請求http://192.168.8.198:19999/www則是對應(yīng)服務(wù)器下的/html/www/index.html,說明 請求帶的uri 中的路徑會自動拼接到root指定的資源目錄后邊。
location /www {
root /html/;
index index.html;
}