2012-07-19 125 views
128

與不同的根文件夾中的多個位置,我希望成爲一個子域的子域和目錄的根URL到我的服務器上的兩個不同的文件夾。下面是簡單的設置,我有和沒有工作...nginx的配置與子域

server { 

    index index.html index.htm; 
    server_name test.example.com; 

    location/{ 
      root /web/test.example.com/www; 
    } 

    location /static { 
      root /web/test.example.com/static; 
    } 
} 

在這個例子中去test.example.com/會帶來/web/test.example.com/索引文件WWW

,並打算test.example.com/static將使索引文件中/web/test.example.com/static

回答

156

您需要使用爲location /staticalias指令:

server { 

    index index.html; 
    server_name test.example.com; 

    root /web/test.example.com/www; 

    location /static { 
    alias /web/test.example.com/static; 
    } 

} 

nginx wiki解釋根和別名更好的區別比我:

注意它可能類似於一見鍾情根指令,但文檔根目錄並沒有改變,只是使用的文件系統路徑請求。請求的位置部分在請求Nginx問題中被放棄。

+42

他不需要'別名'。請閱讀[官方文檔](http://nginx.org/r/alias),而不是用戶填寫的社區wiki。 Quote:*當位置匹配指令值的最後部分時,最好使用root指令*。 – VBart 2012-07-20 16:20:40

+4

這爲我工作,除了它缺少一個尾部斜線。別名應爲: alias /web/test.example.com/static/; – ajma 2014-02-27 05:29:13

+4

@VBart這些文檔確切地說了你引用他們的話,但是他們根本沒有證明這個說法是正確的 - 這看起來像是一種任意的風格選擇。你看到它背後的邏輯理由嗎? – 2015-05-14 09:21:35

35
server { 

    index index.html index.htm; 
    server_name test.example.com; 

    location/{ 
     root /web/test.example.com/www; 
    } 

    location /static { 
     root /web/test.example.com; 
    } 
} 

http://nginx.org/r/root

+6

@全部,無:http://nginx.org/en/docs/http/ngx_http_core_module.html#alias – Athlan 2014-05-14 16:42:49

+0

問:有什麼不同? – TangMonk 2015-12-23 16:11:28

+1

@完全不同:'root /web/test.example.com;'而不是'root /web/test.example.com/static;'。nginx將* location *指定的路徑映射到diretory樹,並且由於路徑和源目錄共享相同的名稱,因此它可以與'root'一起使用。 – rmoestl 2016-04-20 08:35:38

58

的Location指令系統是

就像你希望轉發到開始/static和現在你的數據在/var/www/static

因此,一個簡單的所有要求方法從完整路徑中分離出最後一個文件夾,這意味着

完整路徑:/var/www/static

最後一個路徑:/static和第一條路徑:/var/www

location <lastPath> { 
    root <FirstPath>; 
} 

所以,讓我們看看你做了什麼錯的,什麼是您的解決方案

你的錯誤:

location /static { 
    root /web/test.example.com/static; 
} 

您的解決方案:

location /static { 
    root /web/test.example.com; 
} 
+0

這幫了我的忙:讓我意識到我要麼重命名我的文件夾,要麼設置符號鏈接來使事情有效。 – cjm 2016-10-19 03:30:26

+1

非常感謝你,我正在以這種方式失敗:) – bobmoff 2016-12-05 13:33:55