How do I configure apache to return 404 on unconfigured subdomains?

Viewed 362

I am self-hosting a website on a Debian computer with apache, and in my DNS configuration I have set all subdomains of my domain (*.mydomain.com) to go to the IP of my Debian computer. How do I configure apache so that if someone goes to a subdomain that doesn't have a virtual host, I have a separate file for each subdomain, they get a 404 error instead of seeing the content on the root domain? I have tried editing the 000-default.conf file and put the following in it:

<VirtualHost *:80>
        ServerName null
        Redirect 404 /
</VirtualHost>

<VirtualHost *:443>
        ServerName null
        Redirect 404 /
</VirtualHost>

But now when I got to mydomain.com I get the following error:

This site can’t provide a secure connection
mydomain.com sent an invalid response.
ERR_SSL_PROTOCOL_ERROR

Oddly if I go to one of the subdomains that I have configured for mydomain.com it works correctly and I see the page that should be on the subdomain.

2 Answers
 Your connection is not private

error messages comes from the certificate used which is probably not valid for the domain you're connecting to. Wilcard certificates such as *.mydomain.com are valid for 'third-Level.mydomain.com' but NOT for 'somthing.third-Level.mydomain.com' which requires a wildcard like '*.third-Level.mydomain.com'.

You can get free and valid wildcard certificates from Let's Encrypt (https://letsencrypt.org/)

And, instead of adding port 443 to 000-default.conf, use the default-ssl.conf file. Enable default-ssl.conf using a2enconf default-ssl, and then remove the 443 from the 000-default.conf. And then, restart/reload apache using systemctl restart apache2

Related