2012-03-28 107 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