[Nginx, Django]Securing connections with SSL

来源:互联网 发布:蓝点网络 编辑:程序博客网 时间:2024/04/28 11:39

Reference: Django by Example Chapter 13

Create directory under /etc/nginx, and cd to that directory

mkdir /etc/nginx/sslcd /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 = TrueCSRF_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

0 0