Configure SSL on multiple domains/subdomains on an nginx server with Certbot 08-05-2019
Tags: ,

I’m running an nginx server on Ubuntu 16.04 on my Digital Ocean droplet to host my multiple domains & subdomains. I was having trouble configuring SSL with Certbot for multiple domains while forwarding WWW subdomains to non-WWW (using this tutorial), so here’s how I did it.

Prereqs

First, have your domains online and accessible via http. If you are using Ubuntu Server on a Digital Ocean droplet like me, these resources are very helpful.

Note

For this tutorial, we will pretend we have the following domains and we are redirecting each WWW subdomain to the non-WWW version:

First install Certbot

1
2
3
sudo add-apt-repository ppa:certbot/certbot
sudo apt-get update
sudo apt-get install python-certbot-nginx

Allow https traffic through the firewall & block http traffic

1
2
sudo ufw allow 'Nginx Full'
sudo ufw delete allow 'Nginx HTTP'

Backups

Its a good idea to create a backup of your server before running Certbot.

Now, run Certbot to get an SSL cert for each subdomain and domain

1
sudo certbot --nginx -d example.com -d www.example.com -d example.org -d www.example.org

Note:

Redirect non-WWW to WWW

This is what took me a while. Please note, there is almost definitely a better way to do this, so please let me know (bendotbike@gmail.com), although this is what worked for me. Open the site config file (sudo nano /etc/nginx/sites-enabled/example.com)

Certbot has mutilated this file (for one, see nginx - If is Evil), but I can’t complain when it is this easy to get SSL certs. Anyways, scroll to the server block where there are 2 if statements. Edit the body of the if statement that starts with if ($host = www.example.com), to return 301 https://example.com$request_uri.

Now add the following server block to the bottom of your file

1
2
3
4
5
# redirect www -> non-www
server {
server_name www.example.com;
return 301 $scheme://example.com$request_uri;
}

Finalize

Check for config file syntax errors: sudo nginx -t
Restart nginx: sudo systemctl restart nginx