| | | | | | | |

How to deploy a Django App to a Linux Server – Part #2 – SSL & HTTPS


This document continues on our self-hosted Django Application on an Ubuntu Linux server.
How to deploy a Django App to a Linux Server

We will now set up SSL certificates on our server and enable HTTPS on our app.

Basic Setup

SSH into your service and run the following commands:

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-add-repository -r ppa:certbot/certbot
sudo apt-get update
sudo apt-get install python3-certbot-apache

Apache Configuration Files

Change the django_project.conf file:

cd /etc/apache2/sites-available
sudo nano django_project.conf

Uncomment the line for ServerName and enter your domain:

We then need to temporarily comment our the WSGI lines. When we set up SSL on our server, this file will be copied and the WSGI lines will cause conflicts.
We will therefore comment our these lines for now, and then uncomment them once the SSL version of the config file is created.

Save and exit this file.

Set up CertBot

sudo certbot --apache

Follow the instructions. You will be asked a few questions.

Once the setup is complete, you will notice that CertBot had made a copy of our apache2 configuration file.
The file is called something like /etc/apache2/sites-available/django-project-le-ssl.conf.

Additionally, our original configuration file was changes to include some rewrite rules at the bottom of the file. These rewrite rules will redirect any non-SSL calls to our application to the SSL equivalent addresses. We may go ahead and delete the Alias’s and WSGI lines from the original file since they will not be used.

We will now change the newly created SSL configuration file.

sudo nano django-project-le-ssl.conf

Uncomment the WSGI lines.

We now need to allow HTTPS traffic through the firewall and restart our Apache server:

sudo ufw allow https
sudo service apache2 restart

Automatically renewing the SSL certificate

Create the CRON job:

sudo crontab -e 

Add the following line to the file:

30 4 1 * * sudo certbot renew --quiet

The job will be run every month to renew the SSL certificates.

Similar Posts

Leave a Reply

Your email address will not be published.