2012-03-28 106 views
64

我有nginx作爲apache的反向代理。我現在需要添加一個新的子域 ,它將提供來自另一個目錄的文件,但同時我希望我的默認主機的所有位置和proxy_pass指令也適用於子域。nginx子域配置

我知道,如果我從默認主機複製的規則到新的子,將工作,但那裏的子域名的方式來繼承規則? 下面是一個示例配置

server { 
    listen  80; 
    server_name www.somesite.com; 
    access_log logs/access.log; 
    error_log logs/error.log error; 


    location /mvc { 
     proxy_pass http://localhost:8080/mvc; 
    } 


    location /assets { 
     alias /var/www/html/assets; 
     expires  max; 
    } 

    ... a lot more locations 
} 

server { 
    listen  80; 
    server_name subdomain.somesite.com; 

    location/{ 
       root /var/www/some_dir; 
       index index.html index.htm; 
     } 
} 

感謝

回答

76

你可以共用部位從兩個服務器環境移動到另一個配置文件和include。這應該工作:

server { 
    listen 80; 
    server_name server1.example; 
    ... 
    include /etc/nginx/include.d/your-common-stuff.conf; 
} 

server { 
    listen 80; 
    server_name another-one.example; 
    ... 
    include /etc/nginx/include.d/your-common-stuff.conf; 
} 

編輯:這是一個從我的運行服務器上實際複製的示例。我在/etc/nginx/sites-enabled中配置我的基本服務器設置(Ubuntu/Debian上的nginx的普通功能)。例如,我的主服務器bunkus.org的配置文件是/etc/nginx/sites-enabled,它看起來像這樣:

server { 
    listen 80 default_server; 
    listen [2a01:4f8:120:3105::101:1]:80 default_server; 

    include /etc/nginx/include.d/all-common; 
    include /etc/nginx/include.d/bunkus.org-common; 
    include /etc/nginx/include.d/bunkus.org-80; 
} 

server { 
    listen 443 default_server; 
    listen [2a01:4f8:120:3105::101:1]:443 default_server; 

    include /etc/nginx/include.d/all-common; 
    include /etc/nginx/include.d/ssl-common; 
    include /etc/nginx/include.d/bunkus.org-common; 
    include /etc/nginx/include.d/bunkus.org-443; 
} 

作爲一個例子,這裏的/etc/nginx/include.d/all-common文件,該文件從兩個server情境包括:

index index.html index.htm index.php .dirindex.php; 
try_files $uri $uri/ =404; 

location ~ /\.ht { 
    deny all; 
} 

location = /favicon.ico { 
    log_not_found off; 
    access_log off; 
} 

location ~ /(README|ChangeLog)$ { 
    types { } 
    default_type text/plain; 
} 
+1

好主意。我是否需要將指令包裝在另一個指令下,就像我所做的那樣,當我重新啓動nginx時,nginx會抱怨:nginx:[emerg]「location」指令在這裏是不允許的 – Thomas 2012-03-28 11:36:01

+0

我正在編輯我的答案而不是此評論:) – 2012-03-28 15:13:31

+0

那是我試過的,我得到了我提到的錯誤。你有沒有嘗試過,它的工作? – Thomas 2012-03-29 15:04:56