I have a service example.com
that needs to allow users to host a few files in their own subdomain userpage-userabc.example.com
, similarly as does Github with userabc.github.io
.
I currently use Apache, and each time I want to configure a new domain or subdomain, I have to create manually a new <VirtualHost>
, restart the Apache server, etc.
This is not possible here.
Example: if a visitor creates a new account userabc
(added in a database), how to make that the userpage-userabc.example.com
subdomain is available, and automatically serving files from /www/userabc/
or serving http://userpage-userabc.example.com/
with /www/main/index.php?user=userabc
?
Note: *.example.com
already has a wildcard A DNS-record to redirect to my server
What's a simple lightweight tool to do this "dynamic subdomain creation"? (I currently use Apache, PHP, Python, but I can use other tools).
Or is it possible with a single <VirtualHost>
that catches all sudomains *.example.com
and a RewriteRule including the subdomain?
As mentioned in a comment, here are references for Apache, there are multiple ways to do it: Dynamically Configured Mass Virtual Hosting, Dynamic mass virtual hosts with mod_rewrite.
The simplest solution I have found after a few more tests is: one single
<VirtualHost>
with this wildcard
ServerAlias
.With an
.htaccess
containingwe can then do all the routing for each user via PHP:
Benefit: it also works if the final user is using his own custom domain with a CNAME DNS record. Example:
Then in the PHP,
$host
will here showwww.userabc.com
. If this custom domain information is somewhere in the database, we can serve the content accordingly, even if the user is using a custom domain.Note: in the case for which users use their custom domain with CNAME, this is useful to determine which is the default VirtualHost to use when a request comes with a host which is not listed in the
ServerName
directives: Apache default VirtualHost.