Nginx子域配置

标签 nginx subdomain

我有 nginx 作为 apache 的反向代理。我现在需要添加一个新的子域 它将提供来自另一个目录的文件,但同时我希望默认主机的所有位置和 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;
        }
}

谢谢

最佳答案

您可以将公共(public)部分移动到另一个配置文件,并从两个服务器上下文中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;
}

以下是两个 server 上下文中包含的 /etc/nginx/include.d/all-common 文件作为示例:

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子域配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9905378/

相关文章:

lua - 使用 FastCGI 运行 Lua 脚本

python-3.x - PY3 : Flask-Socketio Alternative?

php - Laravel 子域 : single auth across all subs not working?

subdomain - 在 webmin 上创建子域

ruby-on-rails - 设计 - 在子域上登录

wordpress - Nginx 配置更改为使用 WordPress SEO 友好的 URL

angular - Docker/Angular4/Nginx

php - 600+ memcache req/s 问题 - 帮助!

apache - 应用 SSL 证书后子域文件夹重定向不起作用

dns - 如何申请 oracle.com 的子域?