Check if the connection is secure in django with nginx and gunicorn

I’m serving a django application both through http and https, and since it uses Orbited (which listens to different ports for each type of connection), I needed a way to tell from my templates (from a template context processor to be exact) if the client was using http or https.

Using just request.is_secure wouldn’t work, since my project is served by gunicorn through a nginx proxy_pass, and by default, django can’t tell if its being served on a secure connection.

I don’t know if it’s the best way to do it, but this is how I managed to solve it. First I added the line:

proxy_set_header X-Forwarded-Protocol https;

In the nginx configuration, on the server that uses ssl. Then, I modified the configuration of gunicorn, as suggested in the website, with the setting:

secure_scheme_headers={'X-FORWARDED-PROTOCOL': 'ssl', 'X-FORWARDED-SSL': 'on'}

Lastly, from my context processor, I checked the request headers to tell if the connection is http or https:

def is_secure(request):
    return ('HTTP_X_FORWARDED_PROTOCOL' in request.META and 
        request.META['HTTP_X_FORWARDED_PROTOCOL'] == 'https')

And that’s it.

Advertisements

2 thoughts on “Check if the connection is secure in django with nginx and gunicorn

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s