Chapter 5 · 5.2
nginx with a Let's Encrypt certificate
Already familiar with nginx, or using software that comes with an nginx configuration? Then use nginx with certbot. certbot requests the certificate, updates your configuration and renews the certificate automatically.
nginx and a site
anna@web1:~$ sudo apt install nginx
anna@web1:~$ sudo mkdir -p /srv/www/example.com
anna@web1:~$ sudo nano /etc/nginx/sites-available/example.com
server {
listen 80;
listen [::]:80;
server_name example.com www.example.com;
root /srv/www/example.com;
index index.html;
}
anna@web1:~$ sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/
anna@web1:~$ sudo nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
anna@web1:~$ sudo systemctl reload nginx
Always test with nginx -t before you reload. If there is an error in the configuration, nginx will no longer start.
Requesting the certificate
anna@web1:~$ sudo apt install certbot python3-certbot-nginx
anna@web1:~$ sudo certbot --nginx -d example.com -d www.example.com
The first time, certbot asks for your email address and whether you accept the terms. It then updates your server block for https and redirects http to https.
Renewal happens automatically
Let's Encrypt certificates are valid for a short time and are renewed automatically. Check that this works:
anna@web1:~$ sudo certbot renew --dry-run
anna@web1:~$ systemctl list-timers | grep certbot
Let's Encrypt no longer sends reminder emails when a certificate is about to expire. Let Uptime Kuma monitor the validity (see Uptime Kuma: monitor your sites and server).
Please note: Let's Encrypt limits the number of certificates. Want to practise first? Add --test-cert: you will get a test certificate that browsers do not trust, but that does not count towards the limits.
