Redirect all subdomains to main domain inside vhost

apache-2.2redirectsubdomainvirtualhostwildcard-subdomain

I simply want to redirect all subdomains that are not not already mentioned in a vhost's ServerName to redirect to the empty sub domain. I tried to add this to my httpd.conf after all other virtual hosts of this domain.

<VirtualHost *:80>
    ServerName *.example.com
    RedirectPermanent / http://example.com/
</VirtualHost>

The section for the empty sub domain (loaded earlier) reads like this.

<VirtualHost *:80>
    DocumentRoot /var/www/example/htdocs
    ServerName example.com
    <Directory /var/www/example/htdocs>
        Options FollowSymLinks
        AllowOverride All
        Order Allow,Deny
        Allow from all
    </Directory>
</VirtualHost>

After restarting the httpd service, I see 403 Forbidden when pointing my browser to abc.example.com. What am I doing wrong? I hoped there is no need for regex based matching as described in other answers for this simple task.

Best Answer

Just add a block below the main block in your vhost configuration file. Just specify ServerAlias using the wildcard * for the subdomains. Finally, specify the redirect address using RedirectPermanent.

Listen 80
<VirtualHost *:80>
        ServerAdmin webmaster@localhost
        DocumentRoot /var/www/html
        ServerName example.com

        <Directory /var/www/html/>
            Options Indexes FollowSymLinks
            AllowOverride All
            Require all granted
        </Directory>

        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

<VirtualHost *:80>
    DocumentRoot /var/www/html
    ServerAlias *.example.com
    RedirectPermanent / http://example.com/
</VirtualHost>
Related Topic