Securing a LAMP VPS with a Let's Encrypt Certificate
...and Redirecting Everything to HTTPS
I recently acquired a virtual private server running Ubuntu 20.04, and one of the first things I want to do is to secure it with HTTPS. I already have Apache running and the server accessible via HTTP (e.g., with a browser).
I knew beforehand that Let's Encrypt is a nonprofit CA (Certificate Authority) that provides certificates for free, so I decided to use their certificate.
Acquiring the Certificates
Following the instructions on the websites below, I first simply SSHed into my VPS (with PuTTY, on Windows). I then found out that the Certbot tool can be used to manage certificates on "manually administered servers", which obviously includes my VPS.
Nowadays, the preferred way of installing Certbot is snap. My bare-bones Ubuntu install didn't have it pre-installed, so I ran the following commands to install and refresh snap:
sudo apt-get install snapd
sudo snap install core
sudo snap refresh core
I was then able to actually install and prepare Certbot with the following commands (the latter one makes it executable via PATH
):
sudo snap install --classic certbot
sudo ln -s /snap/bin/certbot /usr/bin/certbot
Finally, I was able to actually install the certificates with the sudo certbot --apache
command. I had to enter my email address, read the Let's Encrypt Terms of Service, and provide the domain names I wanted to register (www.mkkekkonen.fi
).
I had some trouble with registering the domain name at first, as I had bought my domain name from a separate hosting provider. I had to go to their control panel and create an A record pointing to my server's IP address. The Certbot tool tests that the server is actually live behind the specified domain name(s). I also had to type the full www.mkkekkonen.fi
as the domain name, meaning that mkkekkonen.fi
(without the www
) did not work.
Redirecting All Traffic to HTTPS
Next, I wanted to redirect all requests to the HTTPS URL. I simply cd
-ed into the directory /etc/apache2/sites-enabled
. It had a file named 000-default.conf
that conveniently included the existing virtual host configuration.
So, I added the following to the configuration:
<VirtualHost *.80>
# ...snip
Redirect permanent / https://www.mkkekkonen.fi/ # added this line
</VirtualHost>
This configuration takes all requests arriving to the default HTTP port with the number 80, and redirects them to HTTPS.
I then restarted Apache with the command sudo service apache2 restart
. Now, manually typing http://mkkekkonen.fi
gets redirected to the HTTPS URL.
Sources:
Let's Encrypt: Getting Started
Certbot: Instructions
Certbot: About
Linuxize: Redirect HTTP to HTTPS in Apache
Image attribution: FLY:D on Unsplash