Useful snippets for managing SSL certificates for Nginx web server

Testing certificate issuing:

server {
    listen 80;
    server_name staging.com ~^(subdomain1.|subdomain2.|)((?<branch>.+).|)staging.com$;

    set $dir "test";
    if ($branch != "") {
        set $dir branches/${branch};
    }
 
    location /.well-known/ {
        autoindex on;
        alias /var/www/$dir/public/.well-known/;
    }

    location / {
        return 403;
    }
}
certbot certonly -d 'staging.com' -d 'subdomain1.staging.com' -d 'subdomain2.staging.com' --webroot --webroot-path /var/www/test/public --staging --non-interactive;

Testing ability to renew cetificate:

certbot renew --cert-name "${BRANCH}.staging.com" --dry-run --non-interactive;

Removing test certificate:

certbot revoke --cert-name staging.com --delete-after-revoke --staging --non-interactive;

Issuing certificate:

certbot certonly -d '${BRANCH}.staging.com'
-d 'subdomain1.${BRANCH}.staging.com'
-d 'subdomain2.${BRANCH}.staging.com'
--webroot --webroot-path /var/www/subdomains/$BRANCH/public
--non-interactive;

Using issued certificate:

server {
    #...
    # ssl
    ssl_certificate /etc/letsencrypt/live/$certname/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/$certname/privkey.pem;

    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
    ssl_ecdh_curve secp384r1;

    ssl_stapling on;
    ssl_stapling_verify on;
    #...
}

Deleting certificate:

certbot revoke --cert-name $BRANCH.staging.com --delete-after-revoke --non-interactive;

Setting up certificate renewal:

SLEEPTIME=$(awk 'BEGIN{srand(); print int(rand()*(3600+1))}'); echo "0 0,12 * * * root sleep $SLEEPTIME && certbot renew -q" | sudo tee -a /etc/crontab > /dev/null
$ cd ..