Brainstorm's snippets (1/258)

  Django & HTTPS tricks

Testing HTTPS in development

sudo pip install django-sslserver

INSTALLED_APPS = [
    ...
    "sslserver",
    ...
]

then:

python manage.py runsslserver 0.0.0.0:8888

Note that for some reason port 8000 hangs; use 8888 instead.

Credits: https://stackoverflow.com/questions/8023126/how-can-i-test-https-connections-with-django-as-easily-as-i-can-non-https-connec#51384868

With NGINX

In your Django settings, set the SECURE_PROXY_SSL_HEADER setting:

SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')

Then, you need Nginx to set the custom header in the reverse proxy. In the Nginx site settings:

location / {
    # ...
    proxy_set_header X-Forwarded-Proto $scheme;
}

This way request.scheme == 'https' and request.is_secure() returns True. request.build_absolute_uri() returns https://... and so on...

Credits: https://stackoverflow.com/questions/8153875/how-to-deploy-an-https-only-site-with-django-nginx#19637196