# cloudflare-realip-nginx: keep nginx’s real-IP list current

cloudflare-realip-nginx is a single bash script, with a systemd timer and an installer, for operators who run nginx behind Cloudflare. It keeps the real-IP trust list current so that nginx, your logs and your rate limits see the visitor's address, not a Cloudflare edge address. The code is at [https://github.com/IndianOpinion/cloudflare-realip-nginx](https://github.com/IndianOpinion/cloudflare-realip-nginx), under the MIT licence. Version v0.1.0 was released on 12 November 2026.

## The problem

Behind Cloudflare, every request reaches nginx from an edge address. Unless nginx is told which addresses to trust and which header carries the visitor's address, it treats the edge as the client. Rate limits keyed on the client address then put many readers into a few buckets, and one abuser throttles everyone on the same edge. Blocklists and logs see Cloudflare, not the attacker.

Cloudflare publishes its ranges as two plain text lists and says they need regular updates. When the local copy goes stale the failure is quiet: a new range is not trusted, and visitors through it show up as the edge again. Nothing errors.

The usual fix is a ten-line cron script. The usual version writes over the live file before testing it, reloads nginx on every run, checks only the IPv4 count, and accepts any line containing a slash as a range. Each of those became a test case here.

## What it does

- Fetches both lists over HTTPS, checks them strictly, and renders a deterministic set_real_ip_from snippet.

- Tests the candidate with nginx, installs it by atomic rename, and reloads nginx only if the content changed.

- Restores the previous snippet if the full nginx test fails after the swap.

- Offers --dry-run, --diff, --status, --verify, --rollback and --release.

- Supports a non-root user with four fixed sudo commands, and an optional metrics file for a Prometheus textfile collector.

## How it works

The tool is one bash file, bin/cloudflare-realip-nginx, run under set -euo pipefail. It has no Python and no jq. Address validation is done in pure bash parsers for IPv4 and IPv6 CIDRs, so there is no dependency whose output differs between distributions.

Each run takes an exclusive flock in the state directory, then does these steps and stops at the first failure:

- Fetch the IPv4 list, then the IPv6 list.

- Validate both lists and render the snippet. There is no timestamp, so the same lists always give the same bytes.

- Compare with the live snippet. If identical, log unchanged and stop without a reload.

- Write the candidate to a dot-named file in a staging directory on the same filesystem, and test it alone with nginx -t against a throwaway configuration.

- Copy the live snippet to a backup, rename the candidate over it, and run the full nginx -t. On failure, restore the backup and exit 4.

- Reload nginx and record the result in a state file.

The staging directory sits outside the include directory so no include glob can see a half-written file. Requiring the same filesystem keeps the rename atomic and keeps the SELinux label.

The snippet is plain nginx configuration:

# Generated by cloudflare-realip-nginx. Do not edit: changes are overwritten.
# Cloudflare IPv4 ranges
set_real_ip_from ...;
# Cloudflare IPv6 ranges
set_real_ip_from ...;
real_ip_header CF-Connecting-IP;

Typical use:

cloudflare-realip-nginx --dry-run --test
sudo cloudflare-realip-nginx
sudo cloudflare-realip-nginx --verify

## Guard rails

- HTTPS only, certificate checks always on, at most three redirects, redirects only to the pinned host, a body size cap. Timeouts, DNS errors, 429 and 5xx are retried with backoff. TLS errors and other 4xx are not.

- Each line must be a CIDR of the right family with no leading zeros, no host bits, and no overlap with private, loopback, link-local, multicast, documentation, carrier-grade NAT or IPv4-mapped space. A default route is refused.

- Range counts must be within bounds. A run that would remove more than half of either family needs --force. If either family fails, nothing is written.

- The tool only overwrites a file whose first line is its own header. --force takes over a hand-written file after backing it up.

- The config file is parsed as data, never sourced. Unknown keys are an error. Commands run as argument arrays, with no eval.

- A rollback holds scheduled runs for seven days or until --release, so the next timer run does not undo it.

- Exit codes are distinct: 2 for fetch, 3 for validation, 4 for a failed nginx test, 5 for a failed reload, 6 for a held lock.

The tool never touches a firewall. The README opens with a section on locking the origin to Cloudflare's ranges, because real-IP only changes what nginx believes about connections from those ranges, and a direct visitor still skips the WAF and rate limits. It warns that closing port 80 silently breaks HTTP-01 certificate renewal, and that closing IPv4 but not IPv6 leaves the origin exposed. It also notes that the ranges are shared by all Cloudflare customers, so an allowlist alone does not stop traffic sent through another account.

## What review changed

- --extra-trusted accepted an IPv4 or IPv6 default route (a prefix of zero), which would let any client set its own address. Both are now refused with exit 1.

- The recovery marker was written before the backup. A crash between the two could make a later recovery restore an older backup. The backup is now written first.

- install.sh --purge ran rm -rf on the state directory named in the config, so a bad value such as /var/lib would have wiped it. It now removes only the files the tool writes, and the directory only if empty.

- After a failed dry run, a second install.sh run said "already installed" and never enabled the timer. In cron mode the cron file was written even when the dry run failed. Both are fixed.

## Limits and what is next

- Cloudflare and nginx only (including OpenResty). No other CDN lists, no Apache, Caddy, HAProxy or Traefik.

- It makes no Cloudflare API calls, so the China network ranges are not included.

- It never touches a firewall, nginx.conf, a server block or a log format. Refreshing a firewall allowlist is a separate job. The repo ships a script that prints the commands for ufw or nftables without running them.

- Containers are documented, not packaged. There is no Windows support.

- There are no open issues on the repo.

Test status: this is v0.1.0. The bats suite had 169 passing tests and one skipped out of 170 in review, using stand-in commands plus integration tests against a local nginx. The parsers were compared with Python's ipaddress module on 3,037 generated and edge-case CIDRs with no mismatches. shellcheck could not be run locally, and the CI workflows (shellcheck, a container matrix) are parked in a pending folder, so CI has not run on GitHub. It has not run on a live site.

## Install

It needs bash 4.2 or later, coreutils, curl 7.52 or later, flock, logger, diff, and nginx 1.18 or later with the realip module.

git clone https://github.com/IndianOpinion/cloudflare-realip-nginx.git
cd cloudflare-realip-nginx
sudo ./install.sh

The installer runs a dry run with the nginx test first and enables the timer only if that passes. --cron installs a cron file instead of the timer.

[All 47 utilities](https://indianopinion.org/blog/open-source/) · [cloudflare-realip-nginx on GitHub](https://github.com/IndianOpinion/cloudflare-realip-nginx)

Canonical: https://indianopinion.org/blog/open-source/cloudflare-realip-nginx/

AI disclosure: Every summary and comment here is written by AI and published automatically, without a person reviewing each article. We do no original reporting. How this works: https://indianopinion.org/ai-use-policy/
