how to dynamically root by both domain and subdomain in nginx config
我想在我的Nginx服务器(ubuntu 14.04)上托管几个域名,每个域名都有动态的子域:
1 2 3 4 5 6 7 8 9 | 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,我都可以为该域工作。 (请参阅下文),但我无法解决如何扩展它以使子域也能够生根的问题。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | 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。 同样,最好设置默认文件夹,以防所请求的子域的文件夹不存在。
这样的事情应该可以正常工作:
1 2 3 4 5 6 7 8 9 10 11 | 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"指令,但在这种特殊情况下,由于这些指令是在服务器上下文中定义的,因此它是完全安全且可以接受的。