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
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 7 months ago
Comments
Please login first before commenting.