【问题标题】:Nginx subdomain configurationNginx 子域配置
【发布时间】:2012-04-11 22:03:56
【问题描述】:

我让 nginx 充当 apache 的反向代理。我现在需要添加一个新的子域 这将从另一个目录提供文件,但同时我希望默认主机的所有 location 和 proxy_pass 指令也适用于子域。

我知道如果我将规则从默认主机复制到新的子域,它会起作用,但是有没有办法让子域继承规则? 下面是一个示例配置

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;
        }
}

谢谢

【问题讨论】:

    标签: nginx subdomain


    【解决方案1】:

    您可以将公共部分移动到另一个配置文件和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;
    }
    

    【讨论】:

    • 好主意。我是否需要将指令包装在另一个指令下,就像我按照您的建议进行的那样,当我重新启动他时,nginx 抱怨说 nginx: [emerg] "location" 指令在这里不允许
    • 几乎我所有的 nginx 配置都包含类似的子配置文件。是的,它确实有效。也许您可以使用include 指令发布您的实际配置——以及包含文件的内容。适当编辑您的原始问题。
    • 我已更新我的答案以包含实际工作的服务器配置文件。
    • 工作正常。我的错。我把这个公用文件放在一个目录中,每个 .conf 文件都会自动加载,这会导致错误。非常感谢
    • 是的,我自己也遇到过这个问题。这就是为什么我选择将所有包含的文件放入/etc/nginx/include.d 中,这不是 Debian/Ubuntu 系统上常见的 nginx 配置文件的来源。
    猜你喜欢
    • 2018-12-19
    • 2013-07-08
    • 2013-12-04
    • 2018-12-22
    • 1970-01-01
    • 2016-08-23
    • 2014-01-24
    • 2017-05-30
    • 1970-01-01
    相关资源
    最近更新 更多