繁体   English   中英

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

[英]how to dynamically root by both domain and subdomain in nginx config

我想在我的Nginx服务器(ubuntu 14.04)上托管几个域名,每个域名都有动态的子域:

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

我希望将www.domain1.com和domain1.com都root到/ 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;
    }
}

您可以扩展正则表达式以包括任何子域,而不仅仅是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”指令,但在这种特殊情况下,由于这些指令是在服务器上下文中定义的,因此这是完全安全且可以接受的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM