Letting Django know about your HTTPS proxy

If you are running a Django application behind a proxy, Django cannot automatically know if encryption is used. This can cause problems e.g. with redirects. Django, not knowing it should use HTTPS, redirects to http://example.com/foobar/ and this might cause a series of other problems. But Django is awesome and you can let Django know if encryption is used or not.

In this example I'm using Nginx. In your proxy settings you'll have to set a header for X-Forwarded-Proto with the current $scheme. This can either be http or https.

proxy_set_header    X-Forwarded-Proto $scheme;  

Nginx is now telling us if it is using http or https in the header. In your settings.py oder settings_local.py you'll now have to tell Django what to look for:

SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')  

With this setting in place Django knows about the usage of encryption now and you are e.g. able to use is_secure() to check this.

If you'd also like to always redirect to https, you can set this:

SECURE_SSL_REDIRECT = True  

Btw… please use Let's encrypt! ;)