Last active
August 1, 2021 16:03
-
-
Save christianwgd/2b46cf6748d137b1e3ca000eb83678b3 to your computer and use it in GitHub Desktop.
django-request log real ip behind proxy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
from django.conf import settings | |
from request.middleware import RequestMiddleware | |
class RequestProxyMiddleware(RequestMiddleware): | |
""" | |
Place this middleware to your project directory and | |
replace the django-request request.middleware.RequestMiddleware | |
with this middleware in the settings MIDDLEWARE | |
""" | |
def process_response(self, request, response): | |
# Get the header field from which to get the real ip | |
# HTTP_X_FORWARDED_FOR is the default for an apache proxy server | |
forwarded_header = getattr( | |
settings, | |
'REQUEST_FORWARDED_ADDR_FIELD', | |
'HTTP_X_FORWARDED_FOR' | |
) | |
ip = request.META.get(forwarded_header, None) | |
if ip: | |
# update REMOTE_ADDR to forwarded header field | |
request.META.update({'REMOTE_ADDR': ip}) | |
return super(RequestProxyMiddleware, self).process_response(request, response) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment