How to deploy an HTTPS-only site, with Django/nginx?

For the 2nd part of John C’s answer, and Django 1.4+…

Instead of extending HttpResponseRedirect, you can change the request.scheme to https.
Because Django is behind Nginx’s reverse proxy, it doesn’t know the original request was secure.

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…

Leave a Comment