X-Forwarded-For spoofing and how to read the real client IP
By Muntaha Shaheen · · 8 min read
Yes, any client can send its own X-Forwarded-For header, so the left-most address in the list is whatever the sender typed. Proxies only append to the header, so everything left of the entry your own proxy added came from the internet and was never checked. To find the real client IP, start from the TCP peer address, which a client cannot forge. If that peer is not a proxy you run, it is the client, and you ignore the header. If it is, read X-Forwarded-For from right to left, skip every address you trust, and use the first one you don't. Join repeated header lines into one list and validate each entry. Trusting the left-most value lets attackers dodge rate limits, bypass access control and feed false addresses to fraud and VPN checks. Nginx real_ip, Express trust proxy and Cloudflare's published ranges all apply this same rule. Once you have the real address, check it on iplogs.com.
Reading X-Forwarded-For safely
Start from the TCP peer address
A client cannot forge it.
Is the peer a proxy you run?
If not, it is the client. Ignore the header.
If it is, read the header from right to left
Join repeated header lines into one list and validate each entry.
Skip every address you trust
The first address you do not trust is the client.
X-Forwarded-For is how a reverse proxy tells your application who connected to it. It is also an ordinary request header, and HTTP lets a client attach any header it likes. Code that takes the first address in the list and treats it as the visitor is reading text the visitor wrote. The safe rule is to trust only the entries your own proxies added, and most of this page is about applying that rule in Nginx, Express and behind Cloudflare.
What is the X-Forwarded-For header?
X-Forwarded-For (XFF) is a de-facto standard request header that carries the original client address through one or more proxies. MDN gives the format as <client>, <proxy1>, <proxy2>: each proxy appends the address it received the request from, so the right-most entry is the most recent hop and the left-most is the original client, "assuming well-behaved client and proxies".
X-Forwarded-For: 203.0.113.195
X-Forwarded-For: 203.0.113.195, 198.51.100.178The header was never standardised. RFC 7239 defines a structured replacement, Forwarded: for=192.0.2.60;proto=http;by=203.0.113.43, but MDN notes it is used much less. Both have the same trust problem.
Can X-Forwarded-For be spoofed?
Yes, and it takes one flag. The client builds the request, so it can include an X-Forwarded-For header before any proxy touches it. A common Nginx setup then appends the real address instead of replacing the header: the $proxy_add_x_forwarded_for variable is the client's own X-Forwarded-For value with $remote_addr added after a comma.
curl -H "X-Forwarded-For: 203.0.113.7" https://app.example.com/loginBehind one Nginx proxy, the application receives:
X-Forwarded-For: 203.0.113.7, 198.51.100.24198.51.100.24 is the real visitor, written by your proxy. 203.0.113.7 is made up. An app that splits on the comma and takes element zero logs, rate-limits and scores the made-up address.
MDN lists what happens when untrusted values feed security decisions: rate-limiter avoidance, access-control bypass, memory exhaustion and other availability problems. An attacker who sends a different fake address on every request gets a fresh rate-limit bucket each time, and an admin route restricted to the office range accepts any request that claims to come from it.
Fraud and VPN checks go wrong the same way. A sign-up from a datacenter VPN claims a home broadband address, and the reputation lookup runs on the claim. Your logs suffer too: abuse reports and incident timelines end up naming an address the attacker picked.
X-Real-IP and CF-Connecting-IP have the same weakness whenever the origin can be reached without passing through the proxy that sets them. A request sent straight to the origin can carry any value.
Why is the left-most IP attacker-controlled?
Because the client writes first and proxies only append. Everything to the left of the entry your own proxy added came from the internet and nobody checked it. Everything to the right of it was written by machines you operate.
MDN goes further: if the server can be reached directly from the internet, even when it also sits behind a trusted reverse proxy, no part of the X-Forwarded-For list is safe for security uses, and those uses must rely only on addresses added by a trusted proxy. RFC 7239 says the same about Forwarded: it "cannot be relied upon to be correct", and even with a list of trusted proxies, the part of the chain recorded before the first trusted proxy cannot be trusted.
The left-most value is acceptable where a fake costs nothing, such as a rough location on an analytics chart. It is never acceptable for rate limits, access control, fraud scoring or bans.
How do I get the real client IP from X-Forwarded-For?
Take the right-most address that is not one of your proxies. Start from the TCP peer address, the one value a client cannot forge. If that peer is not a proxy you run, it is the client and the header is ignored. If it is, walk X-Forwarded-For from right to left, skip every address you trust, and stop at the first one you don't.
MDN describes two ways to configure the walk. With a trusted proxy list, you give the addresses or ranges of your proxies, and the first address from the right that isn't on the list is the client; this keeps working when you add or remove a hop. With a trusted proxy count, you say how many proxies sit in front of the app and count that many entries back from the right. The count is simpler, but it fails quietly if any request can reach the app over a shorter path.
Two parsing details matter. A request can carry several X-Forwarded-For lines, and MDN says they must be joined into one list in order; reading only the first line is a bug. And entries may not be IP addresses at all, because a forged value can be any text, so validate each one.
Most frameworks do this for you, as the sections below show. If yours doesn't, the logic is short. This Node.js version uses the built-in net.BlockList:
import net from "node:net";
const trusted = new net.BlockList();
trusted.addSubnet("127.0.0.0", 8); // local Nginx
trusted.addSubnet("10.0.0.0", 24); // load balancer subnet
trusted.addAddress("::1", "ipv6");
const isTrusted = (ip) => trusted.check(ip, net.isIPv6(ip) ? "ipv6" : "ipv4");
// socketAddr: req.socket.remoteAddress. xff: req.headers["x-forwarded-for"],
// a string (Node joins repeated lines) or an array of lines, in order.
export function clientIp(socketAddr, xff = []) {
let ip = socketAddr.replace(/^::ffff:/, "");
if (!isTrusted(ip)) return ip; // not from our proxy: ignore the header
const hops = [].concat(xff).join(",").split(",").map((s) => s.trim()).filter(Boolean);
for (let i = hops.length - 1; i >= 0; i--) {
if (!net.isIP(hops[i])) break; // junk: keep the last good hop
ip = hops[i];
if (!isTrusted(ip)) break; // first address we don't run
}
return ip;
}The trusted list should hold only addresses your own infrastructure uses: loopback, the load balancer's subnet, your CDN's published ranges. Trusting a whole private range is reasonable only when nothing else on that network can send HTTP to the app.
How do I configure Nginx real_ip correctly?
Use ngx_http_realip_module. It rewrites the client address from a header, but only for connections that come from an address listed in set_real_ip_from. The Nginx docs note the module is not built by default, so check that nginx -V lists --with-http_realip_module.
If Nginx is the edge and visitors connect to it directly, don't read X-Forwarded-For at all. Overwrite whatever the client sent with the address Nginx saw:
location / {
proxy_set_header X-Forwarded-For $remote_addr; # replace, don't append
proxy_set_header X-Real-IP $remote_addr;
proxy_pass http://127.0.0.1:3000;
}If Nginx sits behind a load balancer, trust only that balancer's range and let the module find the client:
set_real_ip_from 10.0.0.0/24; # load balancer subnet only
real_ip_header X-Forwarded-For;
real_ip_recursive on;
location / {
proxy_set_header X-Forwarded-For $remote_addr; # now the visitor
proxy_pass http://127.0.0.1:3000;
}real_ip_recursive decides which entry wins. Off, which is the default, the address is replaced by the last value in the header. On, it is replaced by the last value that is not a trusted address, which is what you want when more than one of your proxies appends to the list. The original peer stays available as $realip_remote_addr for your access log.
How does Express trust proxy work?
Express reads X-Forwarded-For only after you set trust proxy, and the value decides which entry req.ip returns. Give it the addresses of your proxies:
import express from "express";
const app = express();
app.set("trust proxy", "loopback"); // Nginx on the same host
// app.set("trust proxy", ["loopback", "10.0.0.0/24"]); // plus a load balancer
app.get("/whoami", (req, res) => res.json({ ip: req.ip, chain: req.ips }));
app.listen(3000, "127.0.0.1"); // only the local proxy can connectWith a list of addresses, Express checks whether the socket peer is trusted and then walks X-Forwarded-For from right to left until it finds an untrusted address, the same algorithm as above. Binding to 127.0.0.1 closes the direct path, so nothing but the local proxy can talk to the app.
Avoid app.set("trust proxy", true). The Express docs say that with true the client address is the left-most entry, and warn that your last proxy must then remove or overwrite X-Forwarded-For or the client can supply any value. A number such as 1 counts hops from the right, and the docs warn it is only safe when no request can reach the app over a shorter path.
Is CF-Connecting-IP safe to trust?
Only on requests that really came from Cloudflare. Cloudflare sets CF-Connecting-IP to the address that connected to its edge and sends it only on traffic from the edge to your origin. It also appends to X-Forwarded-For: when the visitor sent none, the value equals CF-Connecting-IP; when they sent one, Cloudflare adds the connecting address to the end of it.
Anyone who finds the origin's address can skip Cloudflare and send their own CF-Connecting-IP. Cloudflare's docs cover both halves of the fix: restore the visitor address only for connections from its published ranges, and block all other traffic to the origin at the firewall.
For Nginx, build the trusted list from Cloudflare's published files instead of pasting it by hand:
#!/bin/sh
# Regenerates /etc/nginx/conf.d/cloudflare-realip.conf from Cloudflare's lists.
set -eu
v4=$(curl -fsS https://www.cloudflare.com/ips-v4)
v6=$(curl -fsS https://www.cloudflare.com/ips-v6)
tmp=$(mktemp)
for net in $v4 $v6; do echo "set_real_ip_from $net;"; done > "$tmp"
echo "real_ip_header CF-Connecting-IP;" >> "$tmp"
mv "$tmp" /etc/nginx/conf.d/cloudflare-realip.conf
nginx -t && nginx -s reloadCloudflare says its ranges change rarely and are added to the published list before they go into production, so a weekly cron run is enough. In Express, the same ranges can go into trust proxy next to loopback. Because Cloudflare appends the connecting address to X-Forwarded-For, req.ip then resolves to the visitor without reading CF-Connecting-IP at all.
X-Forwarded-For vs X-Real-IP vs Forwarded
All of them are request headers a proxy writes, so all of them are only as good as the proxy that wrote them and your check that it really did:
| Header | Set by | Format | Trust it when |
|---|---|---|---|
X-Forwarded-For | Each proxy appends | Comma-separated list, client first | You take the right-most address you don't run |
X-Real-IP | One proxy, by convention | Single address | Your edge proxy overwrites it on every request |
Forwarded (RFC 7239) | Each proxy appends | for=, by=, proto=, host= pairs | Same rule as XFF; for may also be unknown or a token like _hidden |
CF-Connecting-IP | Cloudflare's edge | Single address | The TCP peer is in Cloudflare's ranges and the origin refuses everyone else |
How to test your setup for spoofing
Send the forgery yourself and see what the app records. With the /whoami route from the Express example:
# Through the proxy: must print your real address, not 203.0.113.7
curl -s -H "X-Forwarded-For: 203.0.113.7" https://app.example.com/whoami
# Two header lines: both must be read, the answer must not change
curl -s -H "X-Forwarded-For: 203.0.113.7" -H "X-Forwarded-For: 192.0.2.1" \
https://app.example.com/whoami
# Straight at the origin: should not connect at all
curl -s -m 5 -H "X-Forwarded-For: 203.0.113.7" http://ORIGIN_IP:3000/whoamiRepeat over IPv6 if the site has an AAAA record. If any of these prints 203.0.113.7 or 192.0.2.1, the app is trusting the client.
Why spoofing breaks VPN and proxy detection
An IP check is only as good as the address you pass it. If sign-up code sends the left-most X-Forwarded-For value to a VPN detection API, someone on a datacenter VPN can type a home broadband address into the header and get that address's clean score. Resolve the client address with the rules above first, then look it up.
With iplogs that is one POST https://iplogs.com/v1/check call with {"ip": "..."}; the API docs describe the response. The Node.js guide and the Go guide show complete middleware with trusted proxies, caching and timeouts.
Questions people also ask
Can X-Forwarded-For be spoofed?
Yes. It is an ordinary request header, so a client can send any value. Most proxies append to it rather than replace it, so the forged value survives at the start of the list.
Should I use the first or last IP in X-Forwarded-For?
For anything security-related, use the right-most address that isn't one of your own proxies. The first entry is only reliable when every hop, including the client, is trusted, which on the public internet it never is.
Is X-Real-IP safer than X-Forwarded-For?
Only if your edge proxy sets it on every request, overwriting what the client sent, and the app can't be reached any other way. Otherwise it is just as easy to forge.
Does HTTPS prevent X-Forwarded-For spoofing?
No. TLS protects the request in transit, but the client writes the header before encryption, so a forged value arrives intact.
Why does X-Forwarded-For contain multiple IPs?
Each proxy appends the address it received the request from. With two proxies in front of the app you get the client and the first proxy; a forged value adds another entry at the start.
Sources
- MDN: X-Forwarded-For header
- RFC 7239: Forwarded HTTP Extension
- Nginx: ngx_http_realip_module
- Nginx: ngx_http_proxy_module ($proxy_add_x_forwarded_for)
- Express: behind proxies
- Node.js: net.BlockList
- Cloudflare: HTTP headers (CF-Connecting-IP, X-Forwarded-For)
- Cloudflare: Restoring original visitor IPs
- Cloudflare: Cloudflare IP addresses