How to Fix Cloudflared Duplicate IPs in X-Forwarded-For and ClientHost Headers
Issue with Duplicate IPs in Headers
Today I came across an issue in my access logs where every request had a ClientHost of a
duplicated IP address, like 192.168.1.1,192.168.1.1. Requests to my services are proxied
through Cloudflare then through a Cloudflare tunnel using Cloudflared.
Looking into the issue, the field seems to be populated from the
X-Forwarded-For header, which is added by Cloudflare to indicate the original client IP address.
However, it appears that Cloudflared then added the same IP again, resulting in the duplicate entries. This
caused some issues temporarily as other services use the ClientHost field to work correctly.
It seems that the issue started after one of the many security scanners that are constantly probing the
website sent a couple of requests with a forged X-Forwarded-For header containing
127.0.0.1. This was the first IP address that was duplicated in the logs, with the real client
IP address appearing after the forged localhost IP. I'm not 100% sure why that would cause future IPs to
start being duplicated that were not sending a forged header but the fact that the issue started after those
requests makes it seem like this was the trigger.
I was able to resolve the duplicate IP issue and prevent clients from sending forged X-Forwarded-For
headers by configuring a transformation rule in the Cloudflare dashboard to remove the header from incoming
requests before being sent to Cloudflared. Cloudflared will then populate the header with the client IP
address as normal, without the risk of duplicates or forged values.
Cloudflare Transform Rule
Within the Cloudflare dashboard, navigate to the domain then go to Rules > Overview. Then click on Create Rule > Request Header Transform Rule. Set a name for the rule such as 'Remove X-Forwarded-For' and select Custom Filter Expression then set:
- Field:
Hostname - Operator:
wildcard - Value:
*yourdomain.com
A wildcard match will cover all subdomains.
Set the action to Remove and put X-Forwarded-For as the header name. Finally,
give the rule a name and save it.
Now check your access logs and you should see that the ClientHost and X-Forwarded-For
fields are populated with the correct client IP address without duplicates or risk of forged headers.