Automating Nginx SSL with Certbot and Renewal Hooks
Security

Automating Nginx SSL with Certbot and Renewal Hooks

  • AuthorLiam K.
  • Date
  • Time12 minutes

Overview

This guide shows how to obtain Let's Encrypt certificates for Nginx, deploy them safely and automate renewals using Certbot hooks and service reloads. We'll cover common pitfalls and a reliable approach for production servers.

Prerequisites

  • Ubuntu 20.04+ or similar
  • Nginx installed and serving your site
  • Root or sudo privileges
  • Ports 80 and 443 reachable

Install Certbot

Use the OS packages or snap; snaps are recommended for latest releases:

bash
sudo snap install core; sudo snap refresh core
sudo snap install --classic certbot
sudo ln -s /snap/bin/certbot /usr/bin/certbot

Obtain a Certificate (webroot)

If Nginx serves content, use the webroot plugin to avoid stopping the server:

bash
sudo certbot certonly --webroot -w /var/www/html -d example.com -d www.example.com

Automate Deployment

Create a deploy hook that copies certificates and reloads Nginx atomically:

bash
#!/bin/bash
set -e
DOMAIN=$1
CERT_DIR="/etc/letsencrypt/live/\${DOMAIN}"
DEST_DIR="/etc/nginx/ssl/\${DOMAIN}"
mkdir -p "$DEST_DIR"
cp "$CERT_DIR/fullchain.pem" "$DEST_DIR/" \
    && cp "$CERT_DIR/privkey.pem" "$DEST_DIR/"
systemctl reload nginx

Set a Renewal Hook

Tell Certbot to call your deploy script after a successful renewal:

bash
sudo tee /etc/letsencrypt/renewal-hooks/deploy/99-deploy-nginx <<'EOF'
#!/bin/bash
/usr/local/bin/deploy-nginx "$RENEWED_DOMAINS"
EOF
sudo chmod +x /etc/letsencrypt/renewal-hooks/deploy/99-deploy-nginx

Always test reloads and hooks on a staging certificate before switching to production.

Technical Author

Liam K.

Liam K.

Founder of Trivox. Writes about how the platform, the network, and the Amsterdam sites fit together.