Skip to content

Instantly share code, notes, and snippets.

@jtiai
Created February 26, 2013 11:55
Show Gist options
  • Save jtiai/5037954 to your computer and use it in GitHub Desktop.
Save jtiai/5037954 to your computer and use it in GitHub Desktop.
class MultipleProxyLastMiddleware(object):
"""
Middleware to "fix" HTTP_X_FORWARDED_xxx headers for multiple proxy chains.
Picks the *last* element in the proxy list
As in Django docs - https://docs.djangoproject.com/en/1.3/ref/request-response/#django.http.HttpRequest.get_host
"""
FORWARDED_FOR_FIELDS = [
'HTTP_X_FORWARDED_FOR',
'HTTP_X_FORWARDED_HOST',
'HTTP_X_FORWARDED_SERVER',
]
INDEX = -1
def process_request(self, request):
"""
Rewrites the proxy headers so that only the most recent proxy is used.
Meaning of "recent" depends on the environment - it can be the last or first in the list,
in this case - the last one.
"""
for field in self.FORWARDED_FOR_FIELDS:
if field in request.META:
if ',' in request.META[field]:
parts = request.META[field].split(',')
request.META[field] = parts[self.INDEX].strip()
class MultipleProxyFirstMiddleware(MultipleProxyLastMiddleware):
"""
Same as the MultipleProxyLastMiddleware except that it picks the *first* proxy from the list
as the most recent one.
"""
INDEX = 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment