Setting up HTTPS in OpenResty

3 May 2020 Link



Let's Encrypt

Let's Encrypt is a free https certification signing organization. Followed these steps here to install letsencrypt certbot.
The command I used to create a certificate for this site and the other sub-domains was:
> letsencrypt certonly --webroot -w /path/to/amved.com/files -d amved.com -d www.amved.com -w /path/to/karm/files -d karm.amved.com -w /path/to/milindsweb/files -d milindsweb.amved.com
This created the certificate.
Now test the renewal process by typing:
> letsencrypt renew --dry-run
It worked perfectly.
NOTE: to renew a single certificate you can do
> sudo letsencrypt renew --cert-only <domain name> --dry-run
Now setting up the cron-job to do automatic renewals.
> crontab -e
Add the following line in crontab:
0 23 */5 * * /usr/bin/letsencrypt renew > /home/letsencryptrenew.log 2>&1
0 23 * * */1 sh /home/openresty/restartNginX.sh
where the content of restartNginX.sh is:
kill -HUP $( cat /home/openresty/logs/nginx.pid )
Note that the full path of nginx.pid is used. I did not have full path for sometime and the restart used to fail and I used to get certificate expired on my site periodically.

ACME v01 to ACME v02

I got the notice from letsencrypt that my renewal requests were coming in the ACME 01 protocol and they would stop the support for that from June 1, 2020. They asked to upgrade the certbot. I did and reached certbot 0.31.0 in Ubuntu Xenial. From internet searches it seemed it should get the ACME v02 protocol by default. After sometime got the email again. Then I went to /etc/letsencrypt/renewal and in there are the renewal configuration files. I had to update the server in renewalparams section from https://acme-v01.api.letsencrypt.org/directory to https://acme-v02.api.letsencrypt.org/directory

NginX configuration

Followed the tutorial here. Added the following lines to the nginx configuration file for this site:

  server {
	listen 443 ssl;
	server_name *.amved.com amved.com;
	ssl_certificate /path/to/the/certificate/fullchain.pem;        # usually like /etc/letsencrypt/live/amved.com/fullchain.pem;
	ssl_certificate_key /path/to/private/key/privkey.pem;       # usually like /etc/letsencrypt/live/amved.com/privkey.pem;
  }

NOTE
After setting the cronjob the certificate renew happens but the server should be restarted in order for it to use the new certificates so also add the restart server command in the crontab.

Openresty

In the lua controllers for each domain I enabled to https I simply redirected requests received via http (ngx.var.https == "") to the https url. Thus all http requests were no redirected to https