0

Is it possible to redirect all 404 subdomain result to the root domain in apache2? Im using a wildcard subdomain entry in my DNS provider, and apache is set to fetch the site in the folder with the same name as the subdomain. But I would also like it to be able to redirect its self to the root domain if there is no folder.

NameVirtualHost *:80

# Root domain
<VirtualHost *:80>
        ServerName example.com
        ServerAlias www.example.com
        DocumentRoot /var/www/example.com/public
</VirtualHost>

# Wildcard subdomains
<VirtualHost *:80>
        ServerAlias *.example.com
        VirtualDocumentRoot /var/www/%0/public
        # Redirect to root if `$0` folder doesn't exist
</VirtualHost>

1 Answers1

1

Let's rewrite when the folder isn't there

# Redirect to root if `$0` folder doesn't exist
RewriteEngine on
RewriteCond /var/www/%{SERVER_NAME}/public/ !-d
RewriteRule . http://www.example.com/ [R=301,L]

I tried using DOCUMENT_ROOT, but didn't succeed

# RewriteCond %{DOCUMENT_ROOT} !-d
Gerard H. Pille
  • 2,569
  • 1
  • 13
  • 11
  • Awesome thank you! That works perfectly. I also had to enable the rewrite mod using `sudo a2enmod rewrite`. So just in case anyone else has this issue, they know how to enable it. Thanks again! – Mr. Simmons May 19 '20 at 00:38