Force SSL/HTTPS on Apache2 within VirtualHosts

At the end of this brief tutorial, you should be able to redirect all non-https traffic to https, keeping the URLs intact. This assumes you already have VirtualHosts configured for your domain.

 

Let’s start with some commands. Open up your terminal and run the following:

sudo a2enmod rewrite
sudo a2enmod ssl

 

Edit your vhost file. You should be able to find it in the /etc/apache2/sites-available/ directory. Update <VirtualHost *:80>, change port 80 to secure port 443. Add a new port 80 block. It should look something like this:

<VirtualHost *:80>
        ServerName www.example.com
        Redirect permanent / https://www.example.com/
</VirtualHost>

 

Edit your VirtualHost 443 block, be sure to include the following:

<VirtualHost *:443>
        …
        SSLEngine On
        SSLCertificateFile /etc/apache2/path/to/your/creds.crt
        SSLCertificateKeyFile /etc/apache2/path/to/your/creds.key
        …
</VirtualHost>

 

When done, restart apache: sudo service apache2 restart

Leave a Reply

Your email address will not be published. Required fields are marked *