Letsencrypt and NGINX

How to run Letsencrypt next to nginx, not using the sandalone mode and also having nginx serving your websites through SSL.
It’s really simple, and easy! First..

Step 1

First you need letsencrypt, a good location would be the /etc/ but you can use any location you like.

1
2
cd /etc/
git clone https://github.com/letsencrypt/letsencrypt

Step 2

Create a handy script you can use to renew or request new certificates.

1
2
3
4
5
6
7
#!/bin/bash
# Make Letsencrypt Requests Easier
# /etc/Letsencrypt/easy.sh
#
export DOMAINS="-d domain1.com -d sub.domain2.com -d sub2.domain2.com"
export DIR=/tmp/letsencrypt-auto
mkdir -p $DIR && ./letsencrypt-auto certonly $1 --server https://acme-v01.api.letsencrypt.org/directory --webroot --webroot-path=$DIR $DOMAINS

make the script executable

1
chmod +x /etc/letsencrypt/easy.sh

Step 3

Add a location entry in Nginx to capture the letsencrypt check (if you are the real owner of the domain you are requesting a cert for).
In /etc/nginx/sites-available/default or the config you use for your domain add the following location in a port http 80 listener block:

1
2
3
4
location /.well-known/acme-challenge {
default_type "text/plain";
root /tmp/letsencrypt-auto;
}

Restart/reload Nginx.

Step 4

Run the Letsencrypt script (it will run an update first and install some python packages from the repo and extra packages in a virtualenv, so they are not mixed into the main-fs) and the output should be positive about the cert creation.
If there were any issues they are listed in the console (if there are any: probably related to the nginx location not working properly, so you can debug it yourself).

1
2
3
4
5
6
7
# get new certs
cd /etc/letsencrypt/
./easy.sh

# renew after 3 months (letsencrypt certs are valid 3 months)
cd /etc/letsencrypt/
./easy.sh --renew

Step 5

Configure the new certificates in your system, you can find them in the directory /etc/letsencrypt/live/yourdomain.
Maybe not the most secure way but to get access to the certificates with other services (like nginx and exim) change the rights for the following directories:

1
2
chmod 755 /etc/letsencrypt/archive
chmod 755 /etc/letsencrypt/live

Now you can add the following paths to your configurations:
nginx

1
2
3
ssl_certificate /etc/letsencrypt/live/yourdomain/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/yourdomain/privkey.pem;
ssl_trusted_certificate /etc/letsencrypt/live/yourdomain/chain.pem;

exim4 /etc/exim4/exim4.conf.template

1
2
MAIN_TLS_PRIVATEKEY = /etc/letsencrypt/live/yourdomain/privkey.pem
MAIN_TLS_CERTIFICATE = /etc/letsencrypt/live/yourdomain/fullchain.pem

dovecot /etc/dovecot/dovecot.conf

1
2
ssl_cert = </etc/letsencrypt/live/yourdomain/privkey.pem
ssl_key = </etc/letsencrypt/live/yourdomain/fullchain.pem

Happy sslling :-)