2015-06-08 59 views
-1

我有一個在Apache上運行的Web應用程序,其中虛擬主機文件配置爲將請求路由到子域到特定文件夾。而不是每次創建一個子域的時間來修改host文件,這使我動態路由的URL相關的文件夾(用包羅萬象如果文件夾不存在) -將Apache VirtualHost轉換爲動態子域的nginx服務器塊

<VirtualHost *:8080> 
    ServerName localhost.com 
    ServerAlias *.localhost.com 
    VirtualDocumentRoot "/var/www/clients/%1" 
    ErrorLog "logs\errors.log" 
    <directory "/var/www/clients/%1"> 
     Options Indexes FollowSymLinks 
     AllowOverride all 
     Order Deny,Allow 
     Deny from all 
     Allow from all 
    </directory> 
</VirtualHost> 

我想將上述內容轉換爲nginx,但無法找到從URL中提取子域的正確邏輯,然後在配置文件中設置root變量。

如果root的路徑不存在,任何人都可以幫我寫一個nginx的server {}塊,以及一個catch-all塊嗎?

+0

'server {^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ root var/www/clients/$ 1; }' – JASSY

回答

1

在server_name中使用一個命名正則表達式捕獲,您可以稍後參考。

server { 
    listen 8080; 
    server_name ~^(?<subdir>.*)\.localhost\.com$ ; 

    set $rootdir "/var/www/clients"; 
    if (-d "/var/www/clients/${subdir}") { set $rootdir "/var/www/clients/${subdir}"; } 
    root $rootdir; 
} 

什麼你正在做的是設置默認的根目錄到一個變量$rootdir然後如果$subdir的子目錄覆蓋掉。

+0

非常感謝。不幸的是,它不能按預期工作。在'/ var/www/clients'目錄下,我有一個包含index.html的目錄'client1'。我在catch-all目錄下也有一個index.html。如果我導航到'http:// client1.localhost.com',nginx正在返回catch-all頁面(即直接到$ rootdir而不是$ rootdir/client1)。 – JASSY

+0

我已經切換了設置。默認現在應該工作 – pensivepie

+0

我已經改變了'server'塊'{服務器 \t聽8080; \t服務器名* .localhost.com; \t如果(-d「的/ var/WW /客戶/ $子目錄「){set $ rootdir」/ var/www/clients/$ subdir「;} \t if($ rootdir ==」「){set $ rootdir'/ var/www/clients';} \t root $ rootdir; } '但是當我嘗試用'sudo service nginx restart'重新啓動nginx時,它失敗。 – JASSY