Login

Enable AWS ELB with SSL Termination

Author:
zvikico
Posted:
June 28, 2011
Language:
Python
Version:
1.3
Score:
0 (after 0 ratings)

When using Amazon's ELB with SSL termination, Django needs to know that the requests are secure. You need to use the special indication given on the request (HTTP_X_FORWARDED_PROTO) to determine that. This middleware will do that for you.

The second part is forcing requests to HTTPS in case they are not. This part is not mandatory and could probably be done using configuration rules in your HTTP server. Note that I did it for the specific site, simply to avoid redirecting requests which are not of interest in the first place.

This snippet is based on work done in Django-Heroism.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
from django import http

class CloudMiddleware(object):
    def process_request(self, request):
        if 'HTTP_X_FORWARDED_PROTO' in request.META:
            if request.META['HTTP_X_FORWARDED_PROTO'] == 'https':
                request.is_secure = lambda: True
                return None

        host = request.get_host()
        if host.find('example.com') >= 0:
            new_url = 'https://%s%s' % (host, request.get_full_path())
            return http.HttpResponsePermanentRedirect(new_url)

        return None

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

Please login first before commenting.