How to configure HTTPS on Apache2

An important step when deploying an Apache2 server is the transition from the HTTP protocol to HTTPS. This allows for the encryption of data between the client and the server to protect its content from being transmitted in plain text over the internet.

Take control of your Apache server and install certbot to request a certificate from Let’s Encrypt.

apt-get install certbot

Request the certificate for your domain.

certbot certonly --apache

Be careful when requesting a certificate; you must redirect port 80 to your Apache server.

Your certificate will be located in /etc/letsencrypt/live/mywebsite/

Modify the configuration file of your site in Apache.

nano /etc/apache2/sites-available/mywebsite.conf

Then add the following configuration, adjusting it to your needs.

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

<VirtualHost *:443>
        ServerName mysite.com
        ServerAlias www.mysite.com
        DocumentRoot "/var/www/mysite"
        SSLEngine on
        SSLCertificateFile  /etc/letsencrypt/live/mysite/mycertificate.pem
        SSLCertificateKeyFile  /etc/letsencrypt/live/mysite/mykey.key
        <FilesMatch "\.(cgi|shtml|phtml|php)$">
        SSLOptions +StdEnvVars
        </FilesMatch>

        <Directory "/var/www/mysite">
                Options +FollowSymLinks
                AllowOverride all
                Require all granted
                SSLOptions +StdEnvVars
        </Directory>

        ErrorLog /var/log/apache2/error.mysite.com.log
        CustomLog /var/log/apache2/access.mysite.com.log combined
        LogLevel info
</VirtualHost>

Enable the SSL module.

a2enmod ssl

Then finally restart Apache.

systemctl restart apache2.service 

Don’t forget that HTTPS uses port 443. Therefore, remember to redirect this port from the WAN to your Apache server.

Your site is now HTTPS-enabled, and if you try to access it via http://, you will be automatically redirected to https thanks to the redirection performed by this line in the conf file.

Redirect permanent / https://mysite.com/

Leave a Comment