Skip to content

NGINX real client IP: trust the peer before the header

Trace the source of the address assertion before logs, rate limits and applications rely on it.

Dopstack Engineering

· 9 min read

Original conceptual illustration of a proxy trust gate that checks the peer before accepting its address assertion, with a forged header label rejected.

Quick answer

NGINX should accept a forwarded client address only from a peer that is authorized to supply it. Define the trusted proxy chain, configure the matching real IP behavior, and preserve both the effective client and transport peer in logs. Then pass a deliberate identity contract downstream instead of letting every application reinterpret the raw header.

NGINX should accept a forwarded client address only from a peer that is authorized to supply it. Define the trusted proxy chain, configure the matching real IP behavior, and preserve both the effective client and transport peer in logs. Then pass a deliberate identity contract downstream instead of letting every application reinterpret the raw header. [1][2][3]

Which address does NGINX actually know?#

NGINX knows the address of the peer that connected to it. Behind a load balancer, that peer can be infrastructure rather than the visitor. The real IP module can replace the effective client address using a configured header, but that replacement is meaningful only when the sender and header provenance are trusted. [1]

An incoming X-Forwarded-For value is initially request data. A visitor can submit one just as they can submit another ordinary HTTP header. Its presence does not establish who wrote the listed addresses or which of them represents the visitor. The deployment needs a rule about which intermediaries may make that assertion.

The failure often first appears in logs: every access log shows a load balancer address, or all visitors share a rate-limit bucket. Fixing that symptom by trusting every source may produce plausible-looking logs while allowing an attacker to choose the effective client address. Diagnose the communication path before changing the directive.

Draw the actual route from the public listener to the application. Include the CDN, regional load balancer, internal proxy and any alternate ingress. For each hop, record the observed socket peer, which header it reads, whether it replaces or appends values, and which sources can reach its listener. The arrows need a header policy before they can justify trust.

Follow a forged header through a known chain#

Scenario: a visitor at 198.51.100.24 sends a forged X-Forwarded-For value of 192.0.2.99. An edge proxy at 203.0.113.10 appends its observed visitor address. An internal load balancer at 10.44.0.7 appends the edge’s address before forwarding to NGINX. These are fictional documentation addresses, not provider ranges or a captured customer request.

The origin sees:

text
Socket peer:       10.44.0.7
X-Forwarded-For:   192.0.2.99, 198.51.100.24, 203.0.113.10
                   forged      visitor        edge

If both the load balancer and edge are trusted to construct this chain correctly, recursive real IP processing starts with the trusted transport peer and finds the last non-trusted address in the supplied chain. In this scenario it reaches the visitor address before the forged prefix. The correctness depends on the stated behavior of the intermediaries, not on the header looking syntactically reasonable. [1]

Trusting only the load balancer changes the result. The edge address is then the first non-trusted address encountered from the right, so it becomes the effective client. That can be the correct conservative behavior until the edge’s identity and header policy are established. Adding its range merely to make a desired visitor address appear skips that verification.

Disabling recursive processing also changes the interpretation. For a trusted peer, NGINX uses the last address from the configured header rather than searching through the trusted chain. The distinction matters for this multi-hop example. It does not mean recursion is always required for a provider-specific single-address header. [1]

Scenario: the same visitor connecting directly to NGINX should not gain authority by supplying the same header. If the direct peer is outside the trusted set, the effective address should remain that direct peer. A direct-origin network restriction is an additional control, with its own test, rather than a conclusion inferred from real IP configuration.

What should the origin trust?#

Trust the smallest reviewed set of actual proxy sources that can supply the chosen address assertion. Include the required address families and routes. Avoid a whole private network merely because the current load balancer has a private address; unrelated workloads in that network may be able to reach the origin too.

The following fragment expresses the fictional chain. The addresses are placeholders and must not be copied as a provider configuration:

nginx
# Inside the origin's http or intended server context.
set_real_ip_from 10.44.0.7;
set_real_ip_from 203.0.113.10;
real_ip_header X-Forwarded-For;
real_ip_recursive on;

Check that the installed build includes the real IP module, then inspect the effective configuration for inherited or conflicting directives. The NGINX module documentation identifies the build option; package defaults vary, so do not infer support from a configuration example alone. Validate a proposed configuration before a controlled reload. [1]

For a CDN-specific header, use the provider’s documented semantics. Cloudflare’s visitor-IP instructions describe CF-Connecting-IP and the need to maintain its source prefixes. That is a different contract from an arbitrary multi-hop forwarded list. Do not combine a provider header with an unverified generic proxy chain or assume every intervening load balancer preserves it correctly. [6]

Record where the prefix list comes from and who maintains it. A stale list can exclude legitimate new proxy sources; an overbroad one can authorize senders that should never assert identity. Review changes as infrastructure configuration, with syntax checks and acceptance tests, rather than downloading unknown text directly into a live server configuration.

The address also identifies a network observation point, not necessarily an individual. NAT, shared egress, enterprise gateways and privacy services can put many users behind one address. Use account identity and application authorization for user permissions. A restored client IP can support logging and abuse controls without becoming an authentication credential.

How do you keep both identities in logs?#

Log the effective client and original transport peer as different fields. The real IP module exposes the original address through $realip_remote_addr; $remote_addr represents the effective address after the rewrite. Keeping both makes it possible to distinguish an accepted proxy assertion from the connection that carried it. [1]

A focused JSON access-log format can make the distinction explicit:

nginx
# http context; choose an existing managed log path for the server.
log_format identity escape=json
  '{"client":"$remote_addr",'
  '"peer":"$realip_remote_addr",'
  '"xff":"$http_x_forwarded_for",'
  '"request":"$request",'
  '"status":$status}';

access_log /var/log/nginx/identity.log identity;

The log module supports a configured format and escaping. The raw forwarded header remains untrusted evidence even when it is recorded safely. Do not label that field “verified client,” and do not turn a log viewer’s first-address parsing into a second, undocumented identity decision. [3]

Keep raw chains only where their diagnostic value justifies their retention and access. They can contain visitor addresses and arbitrary supplied text. During a rollout, retain enough evidence to compare peer, effective address and downstream interpretation, then follow the organization’s normal logging policy.

Request routing can affect which log configuration applies. NGINX documents that requests are logged where processing ends, which may differ after an internal redirect. Verify the intended log on the actual application path and on relevant error paths, rather than checking only a dedicated health endpoint. [3]

Which headers should the application receive?#

Choose a downstream contract deliberately. An application immediately behind this NGINX instance may need only a canonical client address that NGINX has already resolved. Sending that value in a controlled header can avoid asking the application to repeat the entire external chain analysis.

nginx
# Example location fragment for a private application upstream.
location / {
    proxy_pass http://application;
    proxy_set_header X-Forwarded-For $remote_addr;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header Forwarded "";
    proxy_set_header CF-Connecting-IP "";
}

This example deliberately replaces the downstream forwarded chain with the resolved address and removes alternative identity headers. It assumes the application can be reached only through the authorized NGINX path and is configured to trust that path. If other intermediaries follow NGINX, design the contract for those hops rather than copying this fragment unchanged.

The familiar $proxy_add_x_forwarded_for has different behavior: it appends $remote_addr to an incoming list. That is useful when retaining a chain is the chosen contract, but it preserves the incoming prefix. A downstream application that trusts the leftmost value can then reintroduce the forged address that the origin had correctly rejected. [2]

Follow the address into each middleware consumer, including request logging, abuse controls, application audit events and user-visible session history. Agreement between these consumers is a testable outcome. Merely seeing the expected address in the NGINX access log does not establish that the application uses it.

For routing changes in the same proxy, keep identity work separate from path rewriting. The proxy_pass path-contract guide explains why a valid proxy configuration can still send a different upstream path. During a Gateway API migration, replay the identity assertions as well as the route behavior.

How should you test bypasses and policy consumers?#

Make rollback behavior part of the test. Removing a trusted prefix can return a proxy address as the effective client; that may collapse unrelated visitors into the same abuse-control bucket. Widening the prefix list to restore familiar logs can instead admit an unintended sender. Compare the accepted source set and the address-consuming policies before choosing the rollback configuration.

Keep the source of each assertion in the handoff: transport peer, trusted intermediary policy, selected header and downstream consumer. If the network owner changes the load balancer path later, that record shows which tests must run again. A sample request from the old route is historical evidence, not approval for a newly reachable listener.

Test both a trusted route and a disallowed assertion. The same header value should produce different outcomes when it comes from an authorized intermediary versus an unrelated peer. A test harness that sends every request from an allowlisted address cannot prove the untrusted-peer branch.

Test route or inputExpected observationWhat a failure means
Reviewed proxy chain with forged prefixEffective address comes from the agreed boundaryChain interpretation or proxy provenance is wrong
Direct untrusted peer with forwarded headerHeader cannot choose the effective identityTrust set is too broad or another layer rewrites identity
Direct-origin bypass attemptNetwork policy rejects the unauthorized routeOrigin exposure needs investigation
Missing or malformed assertionDocumented conservative outcomeParser or middleware assumptions need review
Application request after canonical forwardingApp and origin agree on client identityDownstream trust configuration differs
Acceptance evidence for the proxy identity boundary.

Include IPv6 and any alternate listener in the deployment test. Test repeated header fields and malformed lists against the actual installed stack; do not assume a handwritten string-splitting model reproduces all parser behavior. Keep the observed result and server version with the configuration revision.

Rate limiting is a particularly useful consumer test. NGINX limits requests by a configured key, and its examples use the client-address variable. If every request still resolves to the load balancer, visitors can share a bucket. If an attacker can choose the resolved address, that address-based grouping can be evaded. Verify the key actually used by the intended location. [4]

Address-based access rules also deserve a review after a real IP change. The access module evaluates address rules in sequence to the first match. A policy intended to authorize transport peers must not silently become a policy over rewritten visitor identity. Enforce origin reachability at an appropriate network boundary and test it independently. [5]

Finish the rollout with paired observations: the accepted request has the right peer, effective address and application identity; the forged or bypass request cannot acquire that identity. A configuration file that passes syntax validation is necessary evidence, but these behavioral comparisons establish the trust contract.

What else should you verify?#

Should all private addresses be trusted proxies?
Only if every source in that network is authorized to supply the chosen identity assertion. Private addressing alone does not establish that authority. Prefer the reviewed proxy sources and test an unrelated workload on an otherwise reachable network. [1]
Does real_ip_recursive authenticate the visitor?
No. It resolves an address according to the trusted-peer and header contract. That address can represent a shared egress or another intermediary. Keep user authentication and application authorization independent of this network observation. [1]
Should the application use the first forwarded address?
Only if its complete, verified trust algorithm makes that value authoritative. An incoming chain can contain a visitor-supplied prefix. Choose canonical forwarding or a tested chain contract and verify the application’s interpretation against the origin’s effective address. [2]
Does a passing nginx syntax check prove the trust policy?
No. It establishes that the configuration is accepted by that build. Test authorized proxies, untrusted peers, direct-origin access and downstream identity consumers. Preserve the observed peer and effective address so the result can be audited. [1][3]

Technologies

  • NGINX
  • HTTP
  • Reverse proxies

Sources

  1. [1]
    Real IP module, NGINX

    Observed 2026-11-09. Primary reference for claim S1. Rolling documentation; access date is not release date.

  2. [2]
    Proxy module, NGINX

    Observed 2026-11-09. Primary reference for claim S2. Rolling documentation; access date is not release date.

  3. [3]
    Log module, NGINX

    Observed 2026-11-09. Primary reference for claim S3. Rolling documentation; access date is not release date.

  4. [4]
    Limit request module, NGINX

    Observed 2026-11-09. Primary reference for claim S4. Rolling documentation; access date is not release date.

  5. [5]
    Access module, NGINX

    Observed 2026-11-09. Primary reference for claim S5. Rolling documentation; access date is not release date.

  6. [6]
    Restoring original visitor IPs, Cloudflare

    Observed 2026-11-09. Primary reference for claim S6. Rolling documentation; access date is not release date.

Written by

Dopstack Engineering

Engineering team

The engineering team at Dopstack. Illustrative scenarios are composites written to explain a pattern, not accounts of client work.

All articles Website

Get new articles by email

Engineering notes on AI, cloud and SaaS. Occasional, never sold or shared.

Send me new Dopstack Insights articles by email. I can unsubscribe at any time. We’ll email you once to confirm. Privacy

Continue reading