Login

SSL Redirect Middleware

Author:
zbyte64
Posted:
July 14, 2008
Language:
Python
Version:
.96
Score:
3 (after 3 ratings)

Snippet 240 is great, but it does not handle flatpages since flatpages are not technically a view. This operates on the request level, not the view level so it will handle flat pages.

Step 1 Add this class to your MIDDLEWARE_CLASSES

Step 2 Add an entry in settings.py which is a list of regex to match against urls that u want to have ssl:

SSL_URLS = (
 r'/login/',
 r'/home/',
 r'/super-sensitive-information/',
)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
from django.conf import settings
from django.http import HttpResponseRedirect, get_host
import re

SSL = 'SSL'

class SSLRedirect:
    urls = tuple([re.compile(url) for url in settings.SSL_URLS])
    
    def process_request(self, request):
        secure = False
        for url in self.urls:
            if url.match(request.path):
                secure = True
                break
        if not secure == self._is_secure(request):
            return self._redirect(request, secure)

    def _is_secure(self, request):
        if request.is_secure():
            return True

        #Handle the Webfaction case until this gets resolved in the request.is_secure()
        if 'HTTP_X_FORWARDED_SSL' in request.META:
            return request.META['HTTP_X_FORWARDED_SSL'] == 'on'

        return False

    def _redirect(self, request, secure):
        protocol = secure and "https" or "http"
        if secure:
            host = getattr(settings, 'SSL_HOST', get_host(request))
        else:
            host = getattr(settings, 'HTTP_HOST', get_host(request))
        newurl = "%s://%s%s" % (protocol,host,request.get_full_path())
        if settings.DEBUG and request.method == 'POST':
            raise RuntimeError, \
        """Django can't perform a SSL redirect while maintaining POST data.
           Please structure your views so that redirects only occur during GETs."""

        return HttpResponseRedirect(newurl)

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 2 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 10 months, 1 week ago
  5. Help text hyperlinks by sa2812 11 months ago

Comments

ayaz (on November 4, 2008):

Excellent.

Thank you! It works perfectly. Lovely stuff. :)

#

steve-h (on February 11, 2010):

Hi, Thanks for this snippet - very useful! I have it working with flatpages by adding the following method to the SSLRedirect class:

<hr />

def process_response(self, request, response):

    if response.status_code == 404 and request.is_secure():

        return self._redirect(request, False)

    return response
<hr />

This code assumes that you don't want flatpages behind SSL!

Cheers Steve

#

bkeating (on January 26, 2011):

@Steve H, your comment on supporting (or not supporting_ FlatPages was a huge help. I managed to get proper SSL support with Nginx + Gunicorn with this and the help of a few other related snippets.

#

Please login first before commenting.