Congratulations, you just created a new blog on a DigitalOcean droplet using their “One-click apps”! But, security conscious as you are, you want it to run over SSL exclusively, and force traffic from www.example.com
to example.com
for SEO purposes. When running the default letsencrypt
script, as advertized, it only creates and sets up a certificate for a single host. This trips up browsers because you can’t redirect https://www.example.com
to https://example.com
if the former doesn’t also have a valid SSL certificate. This isn’t explained well, but this is what you should run:
1 |
sudo letsencrypt --apache -d example.com -d www.example.com |
This creates and sets up certificates for both (make sure to choose “Force SSL”). Now to add the actual redirect, edit the file /var/www/html/.htaccess
. Add this (I put it right after RewriteEngine On
):
1 2 3 |
# Redirect www. to non-www. RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC] RewriteRule ^(.*)$ https://%1/$1 [R=301,L] |
I couldn’t find anything on keeping the certificates up to date (they always expire after 90 days) on the droplet, so I created a cronjob myself by running sudo crontab -e
and adding this line:
1 |
30 2 * * 1 /usr/bin/letsencrypt renew >> /var/log/le-renew.log |
This tries to renew the certificates every Monday at 2:30 am, and they will only be renewed when they’re due. This way you should always have valid certificates.
Hope this helps anyone struggling with creating certificates for two (sub) domains at once!