Reference: Django by Example Chapter 13
Create directory under /etc/nginx
, and cd
to that directory
mkdir /etc/nginx/ssl
cd /etc/nginx/ssl
Creating a SSL certificate
openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout your_key_name.key -out your_cert_name.crt
You will be asked to enter the following information:
Country Name (2 letter code) []:
State or Province Name (full name) []:
Locality Name (eg, city) []:
Organization Name (eg, company) []:
Organizational Unit Name (eg, section) []:
Common Name (e.g. server FQDN or YOUR name) []:
Email Address []:
The most important field is the Common Name
. You have to specify the domain name for the certificate, it must match the way you access your website.
If you access your website by IP, eg. 10.0.0.1, fill in 10.0.0.1
If you access your website by Domain Name, eg. example.cm, fill in example.com
Configuring Nginx to use SSL
Edit the nginx.conf
file or the file in your sites-enabled
directory and modify the server directive to include the following
SSL directives:
server {
listen 80;
listen 443 ssl;
ssl_certificate /etc/nginx/ssl/your_cert_name.crt;
ssl_certificate_key /etc/nginx/ssl/your_key_name.key;
server_name ip_or_domain_name;
# ...
}
Restart Nginx with the following command:
systemctl restart nginx
Configuring your project for SSL
Django includes some settings specific to SSL. Edit the settings.py
and add the following code to it:
SECURE_SSL_REDIRECT = True
CSRF_COOKIE_SECURE = True
These settings are as follows:
• SECURE_SSL_REDIRECT
: Whether HTTP requests have to be redirected to
HTTPS ones
• CSRF_COOKIE_SECURE
: This has to be set to establish a secure cookie for the
cross-site request forgery protection