Skip to content

Instantly share code, notes, and snippets.

@christianwgd
Last active August 1, 2021 16:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save christianwgd/2b46cf6748d137b1e3ca000eb83678b3 to your computer and use it in GitHub Desktop.
Save christianwgd/2b46cf6748d137b1e3ca000eb83678b3 to your computer and use it in GitHub Desktop.
django-request log real ip behind proxy
# -*- 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