Cloudflare ensures that visitors browsing your site do so in a secure, private and encrypted manner using SSL/TLS. This is done by default by all sites added to Cloudflare. It is also recommended that Cloudflare communicate with your origin server over a secure connection. This involves installing an SSL certificate at your origin and configuring Nginx to use HTTPS instead of HTTP.
You can read more about SSL/TLS here: https://www.cloudflare.com/learning/ssl/what-is-ssl/. Now let’s configure our Raspberry Pi to make its first SSL handshake…
The first step is to generate a new SSL certificate from the Cloudflare Dashboard. To do this, navigate to the SSL tab for your domain, select the “Origin Server” tab, and then click on the “Generate Certificate” button. Leave all the default settings as-is and select next. You’ll now be presented with text fields for a certificate and a private key. Copy them individually into a text editor and save as .pem (for the certificate) and .key (for the private key). You can save these files to the Documents folder. We will name these files makerflare.pem and makerflare.key.
Note that you need to store the .key file safely as it can never be viewed again from the Cloudflare Dashboard. Also note that both files should begin and end with the correct headers:
-----BEGIN PRIVATE KEY-----
-----END PRIVATE KEY-----
Now let’s copy the files to the /etc/ssl folder:
sudo cp /Documents/makerflare.pem /etc/ssl
sudo cp /Documents/makerflare.key /etc/ssl
Nginx also needs to be configured to use SSL. Edit the default file as follows:
sudo nano /etc/nginx/sites-available/default
un-comment the following lines:
listen 443 ssl default_server;
listen [::]:443 ssl default_server;
Then add the following paths to your cert and key files:
Save the file, exit the editor, and restart Nginx as follows:
sudo systemctl stop nginx
sudo systemctl start nginx
systemctl status nginx
Finally, go back to the Cloudflare Dashboard, select the SSL tab, and change the SSL configuration to “Full”. This ensures that Cloudflare communicates with your origin server in a secure manner.
At this point visitors can access your site either via HTTP or HTTPS. However, we can force HTTPS by selecting “Always Use HTTPS” from the SSL -> Edge Certificates tab in the Cloudflare Dashboard.
We have successfully generated certificate and key files from the Cloudflare Dashboard and have turned-on “Always Use HTTPS”. Nginx is also now correctly configured to use both HTTPs and HTTP.