How can I force a VirtualHost in Apache to not listen for undefined subdomains on 443?

by Charlie Schliesser   Last Updated July 02, 2019 04:04 AM

In /etc/apache2/sites-available/example.com:

<VirtualHost *:443>
        ServerName www.example.com
        DocumentRoot /var/www/example.com/htdocs
        SSLEngine on
        SSLCertificateFile /etc/ssl/certs/ssl-cert-snakeoil.pem
        SSLCertificateKeyFile /etc/ssl/private/ssl-cert-snakeoil.key
</VirtualHost>

I also have a virtual host configured for foo.example.com, but that only listens on port 80.

I have the A record for foo.example.com pointing to this same server. If I visit https://foo.example.com in my browser, it loads the Virtual Host for www.example.com. How can I combat this?



Answers 2


This is because you have not setup the SSL for the sub domain foo.example.com and so it uses the www. domain. If you do not want SSL you can simply remove the Virtual Host all together running on port 443, otherwise just add to the configuration the following:

Allow foo.example.com to operate on SSL

<VirtualHost *:443>
        ServerName foo.example.com
        DocumentRoot /var/www/foo.example.com/htdocs
        SSLEngine on
        SSLCertificateFile /etc/ssl/certs/ssl-cert-snakeoil.pem
        SSLCertificateKeyFile /etc/ssl/private/ssl-cert-snakeoil.key
</VirtualHost>

Redirect HTTPS to HTTP

<VirtualHost *:443>
        ServerName foo.example.com
        RewriteEngine on
        RewriteCond %{HTTP_HOST} ^foo.example.com
        RewriteRule ^/(.*)$ http://foo.example.com/$1 [L,R=301]
        DocumentRoot /var/www/foo.example.com/htdocs
        SSLEngine on
        SSLCertificateFile /etc/ssl/certs/ssl-cert-snakeoil.pem
        SSLCertificateKeyFile /etc/ssl/private/ssl-cert-snakeoil.key
</VirtualHost>

Or if you want a 404 Error then use:

<VirtualHost *:443>
        ServerName foo.example.com
        RewriteEngine on
        Redirect 404 /
        ErrorDocument 404 "Page Not Found"
        DocumentRoot /var/www/foo.example.com/htdocs
        SSLEngine on
        SSLCertificateFile /etc/ssl/certs/ssl-cert-snakeoil.pem
        SSLCertificateKeyFile /etc/ssl/private/ssl-cert-snakeoil.key
</VirtualHost>
Simon Hayter
Simon Hayter
March 14, 2013 18:53 PM

Thank you! This post helped me soooooooooooooooo much!

Raven
Raven
July 02, 2019 03:56 AM

Related Questions


Updated February 28, 2016 01:01 AM

Updated October 23, 2016 09:01 AM

Updated May 14, 2018 23:04 PM

Updated October 06, 2016 09:01 AM

Updated July 26, 2015 13:01 PM