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>
<VirtualHost *:80>
ServerName example.com
ServerAlias *.example.com
DocumentRoot /www/example
<Directory />
AllowOverride All
Require all granted
</Directory>
</VirtualHost>
with this wildcard ServerAlias
.
With an .htaccess
containing
RewriteEngine on
RewriteRule ^(.*)$ index.php [QSA,L]
we can then do all the routing for each user via PHP:
<?php
$host = $_SERVER['HTTP_HOST'];
$sname = $_SERVER['SERVER_NAME'];
// parse the subdomain of $host or $sname and deliver
// the content accordingly (using the database)
?>
Benefit: it also works if the final user is using his own custom domain with a CNAME DNS record. Example:
www.userabc.com CNAME userpage-userabc.example.com
Then in the PHP, $host
will here show www.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.