Tuesday, 18 February 2020

Nginx Config File for Web Service with HTTPS Cert Provided by Let's Encrypt

Certbot has a few modes to create free certs:
  • --standalone
    • Certbot needs port 80 to start a temporary server for domain verification
    • Nginx will need to be shut down for a while
    • Not suggested method, big down time during creating or renewing certs
  • --webroot
    • Certbot won't start temporary server
    • Nginx stays intact
    • Suggested method, fast verification, no down time.
  • --certbot-dns-SOMESERVICE
    • Certbot supports domain verification by DNS
    • Some supported plugins available fro Google Cloud, Amazon AWS, etc.
      • --certbot-dns-route53
      • --certbot-dns-google
      • --certbot-dns-digitalocean
      • etc.
    • Not suggested method, DNS verification is slow
Nginx config file for HTTP/HTTPS with cert by Let's Encrypt, using --webroot method,
File /etc/nginx/conf.d/MYDOMAIN.EXT.conf:
server {
  listen 80;
  server_name MYDOMAIN.EXT;

  listen 443 ssl;
  ssl_certificate /etc/letsencrypt/live/MYDOMAIN.EXT/fullchain.pem;
  ssl_certificate_key /etc/letsencrypt/live/MYDOMAIN.EXT/privkey.pem;

  location /.well-known/acme-challenge {
    alias /usr/share/nginx/html/.well-known/acme-challenge;
  }

  location / {
    if ($scheme = "http"){
      return https://$host$request_uri;
    }

    root /some/dir;
    #OR:
    #proxy_pass http://localhost:SOMEPORT;

    #OR:
    #if ($host = "...")         { proxy_pass ... }
    #if ($host ~ "(...)|(...)") { proxy_pass ... }
  }
}


1) Create the file above, comment out the 3 SSL lines, and restart Nginx:
sudo systemctl restart nginx

2) Get cert, and run:
sudo certbot certonly --webroot --webroot-path /usr/share/nginx/html \
--cert-name MYDOMAIN.EXT --domains MYDOMAIN.EXT

3) Got the cert, enable back the 3 SSL lines, and restart Nginx:
sudo systemctl restart nginx

4) Renew cert any time later with:
sudo certbot renew --webroot --webroot-path /usr/share/nginx/html \
--cert-name MYDOMAIN.EXT --expand --domains MYDOMAIN.EXT

No comments:

Post a Comment