Login

SSL Redirect Middleware

Author:
zbyte64
Posted:
July 14, 2008
Language:
Python
Version:
.96
Tags:
middleware ssl redirect
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. SSL Middleware by sjzabel 8 years, 1 month ago
  2. TLS(SSL) middleware, per URL pattern or whole site by robmadole 4 years, 4 months ago
  3. SSL / HTTPS Middleware for Redirection and href Rewriting by DrMeers 4 years, 12 months ago
  4. SSL Redirect Middleware and testing by willhardy 6 years, 9 months ago
  5. Super User Conditional Page Exception Reporting by zbyte64 6 years, 8 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:


def process_response(self, request, response):

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

        return self._redirect(request, False)

    return response

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.