TLS (SSL), WordPress, Apache VHosts, LetsEncrypt, and CloudFlare

It took a little while to get TLS/SSL working with this site as I use CloudFlare, and when I couldn't get it to work, I guessed it was because of CloudFlare, rather than WordPress. The main, persistent error I was getting whenever I enabled SSL in the Apache config was ERR_TOO_MANY_REDIRECTS. Turns out it was actually an error with the (WordPress) redirection all along.

Getting the LetsEncrypt certificate sorted wasn't too much hassle once I worked out that CloudFlare didn't play nicely with the \--apache flag. The \--webroot flag works perfectly though:

sudo letsencrypt certonly --webroot --webroot-path /path/to/website/folder --renew-by-default --email [email protected] --text --agree-tos -d braindetour.com -d www.braindetour.com -d direct.braindetour.com

When I tried to use the \--apache flag, it worked on the \--dry-run but not the actual run.

The certificates get placed in /etc/letsencrypt/live/braindetour.com/

Add the following lines to your Apache .conf file (for me this is in /etc/apache2/sites-available/):

SSLEngine on
SSLCertificateFile /etc/letsencrypt/live/braindetour.com/cert.pem
SSLCertificateKeyFile /etc/letsencrypt/live/braindetour.com/privkey.pem
SSLCertificateChainFile /etc/letsencrypt/live/braindetour.com/chain.pem

and change <VirtualHost *:80> (at the top) to <VirtualHost *:443>.

At this point I had followed various instructions and here, apart from changing the site URL (in the WP Admin console) to https:// from http://, the instructions stopped. This would have been fine, had I not still been getting ERR_TOO_MANY_REDIRECTS in Chrome every time I tried to access the site, over either HTTP or HTTPS.

Various Apache mod_rewrite rules were suggested, including e.g.:

RewriteCond %{HTTPS} !=on RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301] but this didn't have the desired effect.

What worked in the end was adding another VirtualHost within the apache .conf file as follows:

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

This then sorts the redirection properly, and as you can now see, visiting http://www.braindetour.com instantly redirects to the https version.

All kudos to CloudFlare and LetsEncrypt for such excellent products.