Been playing with nginx for about an hour trying to setup mass dynamic virtual hosts. If you ever done it in apache you know what I mean.
Goal is to have dynamic subdom
Based on user2001260's answer, later edited by partlov, here's my outcome.
Bear in mind this is for a dev server located on a local virtual machine, where the .dev
prefix is used at the end of each domain. If you want to remove it, or use something else, the \.dev
part in the server_name
directive could be edited or altogether removed.
server {
listen 80 default_server;
listen [::]:80 default_server;
# Match any server name with the format [subdomain.[.subdomain...]].domain.tld.dev
server_name ~^(?([\w-]+\.)*)?(?[\w-]+\.[\w-]+)\.dev$;
# Map by default to (projects_root_path)/(domain.tld)/www;
set $rootdir "/var/www/$domain/www";
# Check if a (projects_root_path)/(subdomain.)(domain.tld)/www directory exists
if (-f "/var/www/$subdomain.$domain/www"){
# in which case, set that directory as the root
set $rootdir "/var/www/$subdomain.$domain/www";
}
root $rootdir;
index index.php index.html index.htm index.nginx-debian.html;
# Front-controller pattern as recommended by the nginx docs
location / {
try_files $uri $uri/ /index.php;
}
# Standard php-fpm based on the default config below this point
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/run/php/php7.0-fpm.sock;
}
location ~ /\.ht {
deny all;
}
}
The regex in server_name
captures the variables subdomain
and domain
. The subdomain
part is optional and can be empty. I have set it so that by default, if you have a subdomain, say admin.mysite.com
the root is set to the same root as mysite.com
. This way, the same front-controller (in my case index.php
) can route based on the subdomain. But if you want to keep an altogether different application in a subdomain, you can have a admin.mysite.com
dir and it will use that directory for calls to admin.mysite.com
.
Careful: The use of if
is discouraged in the current nginx version, since it adds extra processing overhead for each request, but it should be fine for use in a dev environment, which is what this configuration is good for. In a production environment, I would recommend not using a mass virtual host configuration and configuring each site separately, for more control and better security.