Join our Newsletter — 33% off our NHI Course
Home› Guides› X-Forwarded-For and Proxy Header Trust Guide: Preventing IP…
Guide Web & API Security

X-Forwarded-For and Proxy Header Trust Guide: Preventing IP Spoofing and Allowlist Bypass

PDF for newsletter subscribers · free to read online

← All guides
By NHI Mgmt Group, under the editorial direction of Lalit Choda Updated 27 November 2026 13 min read
On this page

Any application that reads a client IP address from X-Forwarded-For without knowing which proxy wrote each entry is letting the client choose its own IP address. That one mistake turns IP allowlists into suggestions, lets abusers rotate past rate limits, and fills audit logs with addresses nobody can rely on in an investigation. This guide explains how forwarding headers are built, why the leftmost entry is untrustworthy, and the trust model that works: count or list your own proxies, then read from the right. It is written for web developers, platform engineers and application security teams, and stays framework neutral, with configuration examples from common servers and frameworks to show the pattern.

Key takeaways

  • The header is client-writable. RFC 7239 states that forwarding headers cannot be relied upon to be correct, because any node on the path, including the client, can modify them.
  • Read from the right, stop at the first untrusted address. Only entries appended by proxies you control are trustworthy; the first address to the left of your last trusted proxy is the client for security purposes.
  • Direct reachability voids the model. MDN warns that if the server can be reached directly from the internet, no part of the list can be trusted for security uses, even when a reverse proxy also sits in front.
  • Trust is configured per hop. Each layer (CDN, load balancer, ingress, application) needs an explicit trusted-proxy list or hop count; a single trust all setting anywhere re-opens spoofing.
  • Log both addresses. Record the TCP peer and the derived client IP separately so investigations can see what was claimed and what was proven.

How proxy headers work

When a request passes through a reverse proxy, the TCP connection the application sees comes from the proxy, not the user. To preserve the original address, proxies add headers. X-Forwarded-For is the de facto standard; MDN describes its syntax as a comma-separated list, <client>, <proxy1>, ..., <proxyN>, where each proxy appends the address it received the connection from. The rightmost entry is therefore written by the most recent proxy, and the leftmost entry is the original client only if every hop behaved.

HeaderCarriesDefined byTypical consumer
X-Forwarded-ForChain of client and proxy addressesDe facto conventionClient IP for logging, rate limits, allowlists
X-Forwarded-ProtoOriginal scheme (http or https)De facto conventionRedirects, secure cookie flags, HSTS
X-Forwarded-HostOriginal Host headerDe facto conventionAbsolute URL and link generation
X-Real-IPSingle client addressProxy convention, common with nginxSimple single-hop deployments
Forwardedfor, by, host, proto per hopRFC 7239 (Proposed Standard)Structured forwarding information
PROXY protocolClient address at the TCP layer, before HTTPHAProxy specificationTCP load balancers in front of HTTP servers

Two details trip up custom parsers. First, MDN notes a request may carry several X-Forwarded-For headers, which must be treated as one list in order; reading only one is insufficient. Second, entries may carry ports (AWS Application Load Balancer can add the client port when routing.http.xff_client_port.enabled is set) and IPv6 addresses, so parse with a real IP library rather than string splitting alone.

Spoofing and allowlist bypass

The client can send any X-Forwarded-For value it likes. A proxy configured to append will add the real peer address to the right of the forged values, so the forged entries end up on the left. Any code that takes the first entry, or a framework setting that trusts every hop, hands control of the client IP to the client. This is the textbook example for CWE-348 Use of Less Trusted Source, whose demonstrative example is an IP allowlist that trusts X-Forwarded-For when present. When the derived address is used to authenticate or authorise, the weakness is also CWE-290 Authentication Bypass by Spoofing, with CWE-291 Reliance on IP Address for Authentication as a child.

Where the client IP is usedImpact of a spoofed valueControl
Admin or internal-only allowlistsAccess control bypass from the internetDerive IP from trusted hops only; better, require authentication and do not rely on IP alone
Rate limiting and brute-force lockoutAttacker rotates fake addresses to avoid limits; or names a victim's IP to get it blockedKey limits on the trusted client IP plus account or token identifiers
Audit and security logsInvestigations chase forged addresses; attribution failsLog peer address and derived client IP as separate fields
Geo-blocking and fraud scoringLocation checks evadedUse the trusted client IP; treat leftmost values as hints only
Host and scheme headers (X-Forwarded-Host, -Proto)Poisoned password-reset links, redirect loops, cookies issued without SecureTrust these only from known proxies; restrict allowed hosts

MDN lists the consequences of using untrustworthy values as rate-limiter avoidance, access-control bypass, memory exhaustion and other availability problems, and states that leftmost values must only be used where spoofing has no negative impact, for example analytics. AWS gives the same warning in its load balancer documentation: an entry is trustworthy only if a system you control added it.

The parsing rule

MDN describes two safe ways to select a security-relevant address. Both read the combined list from the right.

  • Trusted proxy count: configure the number of reverse proxies between the internet and the application. With one proxy, the rightmost entry is the client; with three, the last two entries are internal and the third from the right is the client.
  • Trusted proxy list: configure the addresses or CIDR ranges of your proxies. Walk from the right, skipping entries that match the list; the first non-matching address is the client.

The list method copes better with paths of different lengths. The count method breaks if any route reaches the application in fewer hops than configured: Express's documentation warns that a client able to take a shorter path can then spoof any value. In both methods, the first step is to check the TCP peer itself: if the connection did not come from a trusted proxy, ignore the header entirely. MDN adds a useful caveat: the address you select may belong to an untrusted intermediate proxy (a corporate egress proxy, for example) rather than the end user, but it is the only address suitable for security decisions.

Configuring trusted proxies

Every common server and framework implements the right-to-left rule if you configure it. The examples below are listed alphabetically and show each product's own setting names, taken from its documentation; the pattern, not the product, is the point.

ProductTrusted proxy settingBehaviour once setWatch for
Apache HTTP Server (mod_remoteip)RemoteIPHeader X-Forwarded-For with RemoteIPTrustedProxy or RemoteIPInternalProxyProcesses right to left and halts at the first address not trusted to present the preceding oneThe documentation states that without trusted proxy directives the module trusts all hosts presenting the header
ASP.NET Core (Forwarded Headers Middleware)ForwardedHeadersOptions: ForwardedHeaders, KnownProxies, KnownNetworks, ForwardLimit (default 1)Accepts headers only from known proxies, consumes entries right to left, keeps the previous address in X-Original-ForClearing the known lists accepts headers from any peer; set AllowedHosts for X-Forwarded-Host
AWS Application Load Balancerrouting.http.xff_header_processing.mode: append (default), preserve, removeAppend adds the client IP to the right of any existing valueTargets must still read from the right and trust only the load balancer's addresses
Express (Node.js)trust proxy: subnet names, addresses, hop count or functionWalks X-Forwarded-For right to left to the first untrusted address for req.iptrue takes the leftmost entry, so the last trusted proxy must overwrite the header
nginx (ngx_http_realip_module)set_real_ip_from CIDRs, real_ip_header X-Forwarded-For, real_ip_recursive onWith recursive on, uses the last non-trusted address in the headerModule is not built by default; with recursive off it takes the last address after a trusted peer

Choosing a trust design

  • Single reverse proxy on a private network: trust that proxy's address, take the rightmost entry, and block direct access to the application port.
  • CDN, then load balancer, then application: trust a list, not a count: the CDN's published egress ranges plus your load balancer subnet. Refresh CDN ranges automatically, since providers change them.
  • Edge proxy you fully control: configure it to overwrite, not append, the header with the peer address, so downstream services receive a single trusted value. Express's documentation describes exactly this requirement when trust proxy is true.
  • TCP load balancer without HTTP awareness: use PROXY protocol between the balancer and the HTTP server, and accept it only from the balancer.
  • Small teams: one proxy and a framework trusted-proxy setting covers most cases. Large estates should define the trust chain once, as code, and test it in every environment because hop counts differ between staging and production.

The Forwarded header (RFC 7239)

RFC 7239, published in June 2014 as a Proposed Standard, defines Forwarded as a structured replacement for the X-Forwarded-* family. Each hop adds an element with up to four parameters: for (the client-facing address), by (the proxy's own interface), host (the original Host) and proto (the scheme). Its main advance is that values from one hop stay together, which the RFC notes is impossible with separate X-Forwarded headers.

  • Same trust problem: section 8.1 states the header cannot be relied upon to be correct. Structure does not make it trustworthy; you still read from the right and trust only your proxies.
  • IPv6 syntax: addresses must be bracketed and quoted, for example for="[2001:db8:cafe::17]", because the colon is not allowed in a token. Parsers that do not handle quoting will mis-read entries.
  • Obfuscated identifiers: section 6.3 allows identifiers beginning with an underscore, such as for=_hidden, to hide internal addresses while keeping traceability.
  • Information leakage: section 8.2 says origin servers should never copy the header into responses, as it can reveal internal network structure.
  • Conversion: section 7.4 describes converting X-Forwarded-For by prefixing entries with for=, and warns conversion may be impossible when several X-Forwarded headers are present because their order relative to each other is unknown.

In practice, support for Forwarded is uneven across proxies and frameworks, and many deployments emit both. Pick one header as authoritative per hop, configure every proxy to strip the other from inbound client requests, and test that a client-supplied value of either never reaches the application unchallenged.

Logging the right client IP

Logs are where a wrong trust model does quiet, long-term damage. An incident responder asking "which address made this request" needs to know what the network proved and what a header claimed.

  • Two fields, always: log the TCP peer address and the derived client IP. Apache's mod_remoteip documents this directly: %a logs the overridden client address and %{c}a the underlying connection address. nginx exposes the original peer as $realip_remote_addr, and ASP.NET Core keeps it in X-Original-For.
  • Keep the raw header: store the full X-Forwarded-For value in security logs (subject to retention rules), so a mis-configured trust setting can be corrected after the fact.
  • Treat it as personal data: MDN and RFC 7239 both flag client IP addresses as privacy-sensitive; apply your logging retention and minimisation rules.
  • Consistency across layers: CDN, load balancer, WAF and application logs should resolve the same client IP for the same request; mismatches point to a trust gap.

Detection and metrics

  • Header from untrusted peers: count requests where a forwarding header arrives from a peer outside the trusted list (ASP.NET Core logs unknown proxies); in a correct design this should be near zero at the application tier.
  • Leftmost and derived mismatch: track the share of requests where the leftmost entry differs from the derived client IP; sudden spikes from one peer suggest spoofing attempts.
  • Private or loopback client IPs: derived client addresses in 127.0.0.0/8 or RFC 1918 space at an internet-facing tier usually mean a trust misconfiguration.
  • Direct-access attempts: connections to application ports from addresses that are not your proxies, which should be blocked at the network layer.
  • Test coverage: percentage of internet-facing services with an automated test that sends a forged header and asserts the derived IP is unchanged.

Implementation plan

  1. Map the chain: for each internet-facing service, list every hop (CDN, WAF, load balancer, ingress, sidecar) with its addresses and whether it appends, overwrites or passes the header.
  2. Close direct paths: restrict application ports so only the last trusted proxy can connect; without this step, nothing else holds.
  3. Configure each hop: set trusted proxy lists in servers and frameworks, prefer lists to counts, and set the edge to overwrite where possible.
  4. Test in staging: send requests with forged X-Forwarded-For, X-Forwarded-Host and Forwarded values and confirm the derived IP, host and scheme match the real path. Repeat in production with harmless requests.
  5. Move security decisions: key rate limits and lockouts on the derived IP plus user or token identifiers; review every IP allowlist and add authentication behind it.
  6. Update logging: add peer and derived IP fields and the raw header; update SIEM parsers.
  7. Roll back safely: if a new trust list breaks legitimate traffic, revert to the previous configuration while fixing the list, but do not fall back to trusting all peers.

Framework mapping

FrameworkReferenceRelevance
MITRE CWECWE-348 Use of Less Trusted SourceChoosing the client-supplied header over the verified peer
MITRE CWECWE-290 Authentication Bypass by Spoofing; CWE-291 Reliance on IP Address for AuthenticationIP allowlists used as authentication
NIST SP 800-53 Rev 5AC-3 Access Enforcement; SI-10 Information Input ValidationTreat headers as untrusted input before use in decisions
NIST SP 800-53 Rev 5AU-3 Content of Audit Records; SC-5 Denial-of-service ProtectionAccurate source in logs; rate limits that cannot be evaded
NIST CSF 2.0PR.PS-04, DE.AE-02Log records fit for monitoring and analysis

Practitioner checklist

  • Document the proxy chain for every internet-facing service, including which hops append or overwrite.
  • Block direct network access to application ports from anything except the last trusted proxy.
  • Configure trusted proxy lists (preferred) or exact hop counts in every server and framework; never trust all peers.
  • Read X-Forwarded-For from the right, combining multiple headers into one list, and stop at the first untrusted address.
  • Strip or overwrite client-supplied forwarding headers at the edge.
  • Trust X-Forwarded-Host and X-Forwarded-Proto only from known proxies and restrict allowed hosts.
  • Key rate limits on derived IP plus account or token, and put authentication behind IP allowlists.
  • Log peer address, derived client IP and the raw header as separate fields.
  • Add an automated forged-header test to each service's pipeline.

Standards and references

Related NHI Mgmt Group resources: Proxies and Forward vs Reverse Proxy Security Guide · Rate Limiting and API Abuse Guide · API Gateway vs Reverse Proxy · Secure Logging Vocabulary and Application Security Events Guide

PDF for subscribers

Take this guide with you

Every section, table and checklist in one PDF, with links to the sources and related guides. Subscribe to our weekly NHI & AI Identity Journal and we’ll email you a download link.

Free weekly newsletter

Subscribe to the NHI & AI Identity Journal

The latest on NHI and Agentic AI security – articles, research, breaches, news and events every week.

Bonus 33% off our NHI Course when you subscribe.

PDF Downloads for Newsletter Subscribers

Get the guide

Enter your details and we’ll email you a download link.

The full guide is free to read online. The PDF is a thank you for subscribing.

Fill in all fields marked * and tick both boxes to continue.