1. 程式人生 > >nginx 中location和root,你確定真的明白他們關係?

nginx 中location和root,你確定真的明白他們關係?

最近公司開發新專案,web server使用nginx,趁週末小小的研究了一下,一不小心踩了個坑吧,一直404 not found!!!!!當時卡在location和root中,但是網上卻比較少聊這方面的關係,一般都是聊location匹配命令(這裡可以看看http://www.nginx.cn/115.html),花了一下午,徹底搞清楚了location和root到底怎樣找到檔案的。

nginx指定檔案路徑有兩種方式root和alias,這兩者的用法區別,使用方法總結了下,方便大家在應用過程中,快速響應。root與alias主要區別在於nginx如何解釋location後面的uri,這會使兩者分別以不同的方式將請求對映到伺服器檔案上。


[root]
語法:root path
預設值:root html
配置段:http、server、location、if

[alias]
語法:alias path
配置段:location

root例項:
location ^~ /t/ {
     root /www/root/html/;
}
如果一個請求的URI是/t/a.html時,web伺服器將會返回伺服器上的/www/root/html/t/a.html的檔案。

alias例項:

location ^~ /t/ {
 alias /www/root/html/new_t/;
}
如果一個請求的URI是/t/a.html時,web伺服器將會返回伺服器上的/www/root/html/
new_t/a.html的檔案。注意這裡是new_t,因為alias會把location後面配置的路徑丟棄掉,把當前匹配到的目錄指向到指定的目錄。

注意:

1. 使用alias時,目錄名後面一定要加"/"。
3. alias在使用正則匹配時,必須捕捉要匹配的內容並在指定的內容處使用。
4. alias只能位於location塊中。(root可以不放在location中)