I have a website (domain.com) and I would like to redirect all my secondary domains (domain2.com, domain3.com) and all the subdomains of these domains (*.domain.com, *.domain2.com...) to the main domain, www.domain.com (because I want the latter to be the only URL to gain access to the site).
For this purpose, I have created an Apache Virtual Host to catch all these possibilities and redirect them (after having configured my DNS, that goes without saying). I put this configuration in a file named "999-catchall" in the folder "sites-enabled" of Apache. NB : I use this name to be sure that it will be the last vhost checked, because I have also my default vhost (000-default for www.domain.com) and a vhost for my webmail (001-webmail for webmail.domain.com).
Here is the content of this "999-catchall" file:
<VirtualHost *:80>
# catch...
ServerName domain.com
ServerAlias domain2.com domain3.com *.domain.com *.domain2.com *.domain3.com
# ...and redirect
RewriteEngine on
RewriteCond %{HTTP_HOST} !^www\.domain\.com$ [NC]
RewriteRule ^(.*)$ http://www.domain.com$1 [R=301,L]
</VirtualHost>
This configuration works for domain.com, domain2.com, *.domain2.com, domain3.com and *.domain3.com but not for *.domain.com. Example : If I type blabla.domain2.com, I'm redirected to www.domain.com, but if I type blaba.domain.com, I'm not (I just have a "Server not found" error).
Is my method correct? Do you see where my mistake is?
EDIT : My mistake, my DNS server wasn't configured properly for *.domain.com. So this configuration works, if it can help someone who would want to do the same thing.