2

I'm trying to encrypt my entire site over SSL. However, I'm not finding a clear cut way to do this with Django 1.4. Does anyone know a solution?

user1408431
  • 69
  • 2
  • 8

2 Answers2

6

You could use a middleware such as those provided in django-secure or you could handle this at the Apache/Nginx/HAProxy level by redirecting all HTTP requests to HTTPS.

Mark Lavin
  • 24,664
  • 5
  • 76
  • 70
  • +1 Though, just do it at the server level. There's no reason to involve Django in that process. – Chris Pratt Aug 03 '12 at 19:09
  • If you have a mix of HTTP and HTTPS then you will most likely need a Django middleware but if everything is going to be HTTPS then you are indeed better off handling this at the server level. – Mark Lavin Aug 03 '12 at 19:20
  • Not to be contentious, but even then, I would say do it at the server level. For example, like most, my admin is served over HTTPS exclusively, but the rest of my site is HTTP. In my nginx conf, I simply redirect any requests to location /admin/ over HTTP to HTTPS. Django is still not involved, and doesn't need to be. – Chris Pratt Aug 03 '12 at 19:34
  • Yes I understand but both approaches are reasonable even if going through Django is sub-optimal. – Mark Lavin Aug 03 '12 at 19:49
  • how can one achieve it at the server level? – user1408431 Aug 03 '12 at 19:53
  • Depends on your server. What are you using? nginx, Apache, etc.? – Chris Pratt Aug 03 '12 at 19:54
  • I'm running everything on Heroku – user1408431 Aug 03 '12 at 20:12
  • You would need to consult the Heroku documentation to see if it's possible to modify the server config and if not then go with the Python based solution. – Mark Lavin Aug 03 '12 at 22:33
  • I think the Python based solution is the answer. However, I keep getting a "This webpage has a redirect loop" error on ALL my pages and I can't find a concise answer to why. – user1408431 Aug 03 '12 at 23:25
3

On apache+django (1.6) this can be done a number of ways but a simple way can be done in the .htaccess or httpd.conf file is:

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URL}

Here's a link for further info on it:

http://wiki.apache.org/httpd/RewriteHTTPToHTTPS

To be sure the session and csrf cookies are not leaked by the client over plain http connections you should ensure that they are set as 'secure cookies' and only sent by the client over https. This can be done as follows in your settings.py file:

CSRF_COOKIE_SECURE = True
SESSION_COOKIE_SECURE = True

An intro to django security, including SSL/HTTPS (a must read):

https://docs.djangoproject.com/en/1.6/topics/security/

Chris Berry
  • 568
  • 7
  • 11