Skip to content

Instantly share code, notes, and snippets.

@Alir3z4
Last active December 16, 2020 13:01
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Alir3z4/84b48b149d4327ef1ab3 to your computer and use it in GitHub Desktop.
Save Alir3z4/84b48b149d4327ef1ab3 to your computer and use it in GitHub Desktop.
When running on AWS Elastic Beanstalk, we suffer an issue where HTTPS requests arriving at the load balancer are propagated to the individual hosts as HTTP requests. If the host issues a redirect it issues it using the same scheme as its incoming request (HTTP) when it should use HTTPS. This issue isn't unique to AWS EB, it's discussed in the co…
from django.http import HttpResponsePermanentRedirect
class SecureRequestPropagationMiddleware(object):
"""
When running on AWS Elastic Beanstalk, we suffer
an issue where HTTPS requests arriving at the load
balancer are propagated to the individual hosts as
HTTP requests. If the host issues a redirect it
issues it using the same scheme as its incoming
request (HTTP) when it should use HTTPS.
This issue isn't unique to AWS EB, it's discussed
in the context of WebFaction hosting in this
Django ticket:
https://code.djangoproject.com/ticket/12043
This middleware addresses the problem, by
using the value of the X-Forwarded-Proto header
to manually set the wsgi.url_scheme header.
"""
def process_request(self, request):
"""
:type request: django.http.HttpRequest
:rtype: HttpResponsePermanentRedirect or None
"""
if 'HTTP_X_FORWARDED_PROTO' in request.META:
request.META['wsgi.url_scheme'] = request.META['HTTP_X_FORWARDED_PROTO']
if request.is_secure():
url = request.build_absolute_uri(request.get_full_path())
if not url.startswith('https://'):
secure_url = url.replace('http://', 'https://')
return HttpResponsePermanentRedirect(secure_url)
return None
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment