如何在nginx配置中通过域和子域动态生根

时间:2014-12-15 15:31:36

标签: linux nginx ubuntu-10.04

我想在我的nginx服务器(ubuntu 14.04)上托管多个域名,每个域名都有子域名:

home/serve/
     domain1.com
        www
        subdomain1
        subdomain2
     domain2.com
        www
        subdomain1
        subdomain2

我希望www.domain1.com和domain1.com都以/ home / serve / domain1 / www和subdomain1.domain1.com为根,以root身份登录到/ home / serve / domain1 / subdomain1。

无论是否使用www,我都可以使用此域名。 (见下文)但我无法解决如何扩展此问题以启用子域生根。

server {
    listen 80 default_server;
    listen [::]:80 default_server ipv6only=on;

    server_name   ~^(www\.)?(?<domain>.+)$;

    root       /home/serve/$domain/www/;

    location / {
        index index.html index.htm index.php;
    }

    location ~ [^/]\.php(/|$) {
      fastcgi_split_path_info ^(.+?\.php)(/.*)$;
      fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
      fastcgi_pass unix:/var/run/php5-fpm.sock;
      fastcgi_index index.php;
      include fastcgi_params;
    }
}

1 个答案:

答案 0 :(得分:4)

您可以扩展正则表达式以包含任何子域,而不仅仅是www。此外,如果所请求的子域的文件夹不存在,最好设置默认文件夹。

这样的事应该可以正常工作:

server_name ~^(?<subdomain>\w*?)?\.?(?<domain>\w+\.\w+)$;

if ($subdomain = "") {
    set $subdomain "www";
}

if (!-d "/home/serve/$domain/$subdomain") {
    set $subdomain "www";
}

root "/home/serve/$domain/$subdomain";

请注意,即使使用“if”指令通常是不可取的,但在这种特殊情况下,它是完全安全且可接受的,因为这些指令是在服务器上下文中定义的。