How to use django-sslify to force https on my Django+nginx+gunicorn web app, and rely on Cloudflare's new free SSL?

前端 未结 1 1690
余生分开走
余生分开走 2020-12-11 08:12

Intro

Cloudflare\'s providing SSL for free now, and I would be a fool to not take advantage of this on my site, and a downright dickhead to break everything in the

相关标签:
1条回答
  • 2020-12-11 08:38

    CloudFlare allows you to enable specific page rules, one of which is to force SSL (by doing a hard redirect). This is a great thing to use in addition to django-sslify or django-secure


    In addition to setting up your SSL redirect, you also need to tell Django to handle secure requests. Luckily, Django provides a decent guide for doing this, but there are a few things that it doesn't mention but I've had to do with nginx.

    In your Django settings, you need to tell Django how to detect a secure request

    SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTOCOL', 'https')
    

    In your nginx configuration you need to set up the X-Forwarded-Protocol header (and the X-Forwarded-For/X-Scheme headers are also useful).

    proxy_set_header X-Scheme $scheme;
    proxy_set_header X-Forwarded-Protocol $scheme;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    

    You also need to proxy the Host header down, so Django is able to read the correct host and port, which is used in generating absolute urls and CSRF, among other things.

    proxy_set_header Host $http_host;
    

    Note that I used the $http_host variable instead of $host or $host:$server_port. This will ensure that Django will still respect CSRF requests on non-standard ports, while still giving you the correct absolute urls.

    As with most things related to nginx and gunicorn, YMMV and it gets easier after you do it a few times.

    0 讨论(0)
提交回复
热议问题