Let's Encrypt Wildcard Certificates with Cloudflare DNS and NGINX

Keith Tweed

April 29, 2019

With NGINX reverse proxies, getting a new SSL certificate with every single subdomain is a pain. However, Let's Encrypt has something that helps with this: Wildcard certificates, which work for every subdomain of a given domain. With Cloudflare DNS, Certbot can use the Cloudflare API to add and remove the DNS verification elements automagically, making setup and renewal super easy.

To start off, install Certbot and the Cloudflare and NGINX Plugins. I'm using Centos, but the package names are the same on Ubuntu/Debian. I'm also installing nano as a text editor, since Centos doesn't come with it out of the box.

sudo yum install certbot python2-certbot-nginx certbot-dns-cloudflare nano

Next, you need to get your API keys from Cloudflare. First, we'll create the file to store it. This file needs to be accessible only by root, so we'll make the file like this:

sudo touch /root/cloudflare_api_keys.ini
sudo chmod 700 /root/cloudflare_api_keys.ini

Log on to your Cloudflare Dashboard, go to your profile, and near the bottom, click on the “View” button next to Global API Key.

Now, edit the file we made before to include your email and API key like this:

dns_cloudflare_email = "[email protected]"
dns_cloudflare_api_key = "your_api_key_here"

Now, run Certbot with a command similar to the following, replacing the necessary details.

sudo certbot --dns-cloudflare --dns-cloudflare-credentials /root/cloudflare_api_keys.ini -i nginx -d "*.example.com" -d example.com --server https://acme-v02.api.letsencrypt.org/directory

That command will walk you through installing the certificates in your NGINX config file automatically, assuming you already have NGINX configured. Simply select the domains you want, and choose whether or not you want HTTP traffic to be redirected to HTTPS. Certbot will take care of modifying your configuration files, so you just have to reload NGINX after to apply the changes.

sudo systemctl reload nginx

To renew your certificates, you can just run certbot renew either manually or in your crontab to renew all of your Let's Encrypt certificates automatically. I recommend testing it first, since it doesn't seem to work on my system. However, running the previous Certbot command does renew the certificates if they need to be renewed.