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:

[fcgi-program:asgi]
# Set Django environment variables
environment=DJANGO_SETTINGS_MODULE="photo_blog.settings.production",AVE_SECRET_KEY="8923hi3ioe892hufe8943sdfhufsehfwe92"

# TCP socket used by Nginx backend upstream
socket=tcp://localhost:8000

# Directory where your site's project files are located
directory=/home/myusername/averyuslaner.com

# 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/averyuslaner.com/privkey.pem:certKey=/etc/letsencrypt/live/averyuslaner.com/fullchain.pem -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
numprocs=1

# Give each process a unique name so they can be told apart
process_name=asgi%(process_num)d

# Automatically start and recover processes
autostart=true
autorestart=true

# Choose where you want your log to go
stdout_logfile=/var/log/asgi.log
redirect_stderr=true

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.