Securing Django + Nginx With TLS

Tags: django lets encrypt nginx

Installing Certbot

We first need to install certbot from Let's Encrypt since that will do most of the hard work for us.

sudo apt-get update
sudo apt-get install software-properties-common
sudo add-apt-repository universe
sudo add-apt-repository ppa:certbot/certbot
sudo apt-get update
sudo apt-get install certbot python-certbot-nginx

Now that certbot it installed, we can grab a certificate. We'll have daphne consume it so we don't need certbot to mess with our nginx file.

sudo certbot certonly --nginx

The tool will prompt you for an email address and ask you to agree to a few things before it saves the certificate.

At this point, I need to update my supervisord config file so Daphne can actually make use of it. That config should like something like this:

# Set Django environment variables

# TCP socket used by Nginx backend upstream

# Directory where your site's project files are located

# Each process needs to have a separate socket file, so we use process_num
# Make sure to update "mysite.asgi" to match your project name
command=/home/myusername/venv/bin/daphne -e ssl:443:privateKey=/etc/letsencrypt/live/ -u /run/daphne/daphnee%(process_num)d.sock --fd 0 --access-log - --proxy-headers mysite.asgi:application

# Number of processes to startup, roughly the number of CPUs you have

# Give each process a unique name so they can be told apart

# Automatically start and recover processes

# Choose where you want your log to go

Daphne can't handle TLS unless you have the correct packages installed for Twisted. To meet those requirements, we'll pip install them:

pip install Twisted[tls,http2]

Then we need to update supervisord:

sudo supervisorctl reread
sudo supervisorctl update

Boom, website secured.