How to Handle Client IP Addresses in Django

Django provides request metadata, including REMOTE_ADDR, through request.META. On a direct connection, that address can describe the client peer seen by the web server. Behind a reverse proxy, it may instead describe the proxy. A separate forwarding header may report an earlier address, but the mere presence of that header in request.META does not make it trustworthy.
Before using a forwarded address for logs or access rules, identify the component that receives outside requests and the component that connects to Django. Configure the first trusted proxy to replace untrusted forwarding values, and protect the path from that proxy to the application against bypass and tampering. Check the connection peer before accepting a forwarded value. Keep peer information available for troubleshooting.
Inspect the Peer Django Actually Sees
An incoming X-Forwarded-For header appears under HTTP_X_FORWARDED_FOR in request.META when the server passes it through. Most HTTP header names are converted to uppercase, with hyphens replaced by underscores and an HTTP_ prefix added. The values come through the deployment server; a header being available does not establish that a trusted intermediary set it.
In a controlled diagnostic request, compare request.META.get("REMOTE_ADDR") with the upstream peer expected by the architecture. If the connection comes from a load balancer, that address may be entirely correct as a peer even though it is not the original visitor. Identify whether a WSGI or ASGI server, web server, or middleware has already transformed the address before Django receives it. Avoid rewriting a value twice.
Identify and Sanitize Forwarded Information
Map every route to the application, including any CDN, public proxy, ingress controller, or internal load balancer in the path. Record which hop appends or replaces forwarding fields and which peers are allowed to do so. A direct request with an arbitrary X-Forwarded-For value must not be able to claim another address. The proxy nearest the untrusted client should remove or overwrite client-supplied fields according to the agreed scheme, and the application should only accept the result from known peers.
The standardized Forwarded header can also contain modified or forged data. A standardized format does not authenticate the sender. The same principle applies to nonstandard forwarding headers. A comma-separated list is not automatically a verified chain, and taking the leftmost entry without defining trusted hops can turn a user-provided string into a security decision.
Avoid a universal helper that assumes every Django deployment uses the same proxy count or header. Different ingress routes may have different lengths. A sound implementation is specific to the server, proxy, and application arrangement and is tested when that arrangement changes. If the proxy or server can set an already validated effective address before Django, document its behavior and preserve the original connection peer in logs.
Validate a Single Address from a Known Proxy
For a simple deployment with one controlled proxy, the application can accept one address from X-Forwarded-For after checking the peer. The following example assumes that the server leaves the actual connection peer in REMOTE_ADDR, and that the proxy overwrites X-Forwarded-For with exactly one IP address. The proxy-to-application connection must also be protected so another system cannot impersonate the proxy or modify the header in transit.
The proxy address 192.0.2.20 is an example reserved for documentation; replace it with your actual proxy address. The parser accepts an IPv4 or IPv6 address string and rejects lists, ports, and IPv6 zone identifiers. Call client_ip(request) from the view or middleware that needs the selected address.
from ipaddress import ip_address
TRUSTED_PROXY = ip_address("192.0.2.20")
def parse_ip(value):
if not isinstance(value, str) or "%" in value:
return None
try:
return ip_address(value.strip())
except ValueError:
return None
def client_ip(request):
peer = parse_ip(request.META.get("REMOTE_ADDR"))
if peer is None:
return None
if peer != TRUSTED_PROXY:
return str(peer)
forwarded = parse_ip(request.META.get("HTTP_X_FORWARDED_FOR"))
return str(forwarded) if forwarded is not None else NoneFor a request from another peer, the function ignores the forwarding header and returns the peer address. For a request from the trusted proxy, a missing or invalid header returns None instead of presenting the proxy as the visitor. Decide explicitly how your application handles that missing address, especially before an access decision.
This example deliberately does not process a chain of proxies. If your deployment sends a comma-separated list, use a parser and trust policy designed for that exact chain, or have a controlled proxy produce a single verified value. Do not change the helper to take the leftmost item merely to make an unexpected header pass validation.
Keep HTTPS Settings Separate from IP Trust
SECURE_PROXY_SSL_HEADER tells Django which proxy-supplied header and value to use when deciding whether request.is_secure() should report HTTPS. The setting does not validate a reported visitor IP. Likewise, ALLOWED_HOSTS checks the request host when Django evaluates request.get_host(); it does not validate HTTP_X_FORWARDED_FOR.
Review the deployment security settings with the proxy configuration, yet test each claim independently: the original scheme, the effective host, the connection peer, and the derived client address. A request can have a correct HTTPS indication and still carry a forged client-address header. Treat these as separate trust decisions rather than one broad notion of a trusted proxy.
Separate Logging from Security Decisions
For operational logs, it can be useful to record both the raw peer address and a derived client address along with a request identifier. That makes it easier to diagnose a misconfigured proxy chain. Limit access to those logs and keep only the address detail needed under the applicable retention policy. Mask or omit personal values when sharing examples.
For rate limiting, fraud controls, or access rules, a spoofable header is unacceptable. Test the behavior through each authorized proxy route and from an untrusted direct route in a controlled environment. Send a deliberately false forwarding value both directly and through the proxy. Confirm that direct input cannot override the peer address and that the proxy replaces the forged value with the address it actually observes. If direct access should be impossible, test that network restriction as well.
Verify and Revisit the Deployment
Record the Django version, ingress path, trusted peer ranges, header sanitation rule, and expected values for each test. When a CDN, load balancer, or container network changes, repeat the tests; an address list or assumed hop order can become stale. Do not treat an IP address as a unique identity or a precise location. NAT, shared networks, and VPNs can all alter the visible address.
Include valid, absent, malformed, and forged forwarding values in those tests. Compare the results with the recorded expectations before using the derived addresses for automated decisions.







