Skip to content

Cloudflare in front of your own HAProxy or Nginx load balancer

Running your own LB behind the Cloudflare proxy means two hops between the visitor and the app. How to carry the real client IP through both, split health-check duties, and tune keep-alive so the layers cooperate.

Cloudflare in front, your own HAProxy or Nginx load balancer behind it, app servers behind that: a solid, common architecture — and one where three things quietly break if nobody designs them. The client IP arrives twice-wrapped and your backends log the LB’s address; nobody health-checks the LB itself because “Cloudflare is in front”; and mismatched idle timeouts between Cloudflare, the LB, and the backends produce sporadic 502s that resist casual debugging. All three have clean fixes.

What’s happening

The request path is client, Cloudflare edge, your LB, app backend — two proxy hops. Cloudflare puts the visitor’s address in the CF-Connecting-IP header and appends to X-Forwarded-For. Your LB must do two jobs at that boundary: trust those headers only when the TCP peer is genuinely Cloudflare (otherwise anyone can forge a source address), and then pass a trustworthy client IP down to the backends in a header they log and rate-limit on.

Health checking splits by layer. Without the paid Load Balancing add-on, Cloudflare does not probe your origin — if your LB goes down, Cloudflare keeps connecting and returns 52x errors to visitors. Your LB health-checks its backends; something external must health-check the LB; Cloudflare checks nothing.

Keep-alive is the third seam. Cloudflare maintains persistent connections to the origin and reuses them aggressively. If your LB’s idle timeout is shorter than the reuse window, the LB closes a connection just as Cloudflare sends the next request on it — that race surfaces as intermittent 520/502 responses under moderate load, the classic signature of timeout inversion.

What to check first

  • What the backends currently log. If access logs show one LB IP for all traffic, rate limiting, fail2ban, and analytics downstream are already wrong.
  • Whether the LB restricts 443 to Cloudflare ranges. Header trust and firewall allowlisting are the same decision made in two places; see allowlisting Cloudflare IPs at the origin firewall.
  • Current idle timeouts at every layer. LB client-side, LB server-side, backend keep-alive. Write the three numbers down; the bugs live in their ordering.

How to verify

# What client IP does a backend actually see? Add a debug header at the LB, then:
curl -s https://www.example.com/whoami | grep -iE 'x-forwarded-for|cf-connecting-ip'

# Is the LB reachable only from Cloudflare?
curl -m 5 -skI https://<lb-public-ip>/ -H 'Host: www.example.com'   # should time out

# Watch for keep-alive races: 520/502 patterns in the LB log
grep -cE ' (502|520) ' /var/log/haproxy.log

# Confirm the ranges the trust list is built from
curl -s https://www.cloudflare.com/ips-v4

The fix

  1. Nginx as the LB: restore the real IP at the first hop. Use the realip module, seeded from the published ranges, and trust CF-Connecting-IP:

    # /etc/nginx/conf.d/cloudflare-realip.conf (regenerate from cloudflare.com/ips)
    set_real_ip_from 173.245.48.0/20;
    # ...one line per published IPv4 and IPv6 range...
    real_ip_header CF-Connecting-IP;

    Then pass it downstream: proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; and proxy_set_header X-Forwarded-Proto $scheme;. Backends log X-Forwarded-For and never trust it from any source but the LB. The single-server variant of this setup is covered in Nginx real IP behind Cloudflare.

  2. HAProxy as the LB: rewrite the source from the header, gated by an ACL. HAProxy has no realip module; the idiom is set-src:

    # /etc/haproxy/haproxy.cfg
    frontend fe_https
        bind :443 ssl crt /etc/haproxy/certs/example.com.pem
        acl from_cf src -f /etc/haproxy/cloudflare_ips.lst
        http-request set-src hdr(CF-Connecting-IP) if from_cf
        default_backend be_app

    Regenerate /etc/haproxy/cloudflare_ips.lst from the published URLs with the same refresh job that feeds the firewall. After set-src, HAProxy’s own logs, stick tables, and rate limiting all key on the real visitor.

  3. Split the health checks by layer. LB to backends: option httpchk GET /healthz in HAProxy or max_fails/fail_timeout (or an active-check module) in Nginx upstreams. LB itself: an external probe that does not transit Cloudflare — the pattern is detailed in monitoring origin health behind the proxy. If you have no external monitor, the first notice of a dead LB is a visitor screenshotting a 522.

  4. Order the idle timeouts: each layer outlives the one in front. Rule of thumb: backend keep-alive timeout longer than LB server-side idle timeout, LB client-side idle timeout comfortably above 100 seconds so Cloudflare’s connection reuse never races your close. HAProxy: timeout client 305s, timeout server 305s, timeout http-keep-alive 300s. Nginx LB: keepalive_timeout 620s on the Cloudflare-facing side, plus keepalive 32 connections in the upstream block with proxy_http_version 1.1 and a cleared Connection header so backend connections are reused too.

  5. Terminate TLS deliberately at each hop. Cloudflare to LB: Full (strict), with a certificate the LB serves — a Cloudflare Origin CA certificate is fine here because only Cloudflare connects to it. LB to backends on a private network: your call, but be consistent, and keep X-Forwarded-Proto accurate so apps generate correct redirect and cookie flags.

When this approach is wrong

If the LB tier exists only to fail over between two origins, the managed Load Balancing add-on may replace it outright — one less 24/7 component you own; the broader trade-off is mapped in Cloudflare LB vs self-hosted multi-region. If the LB fronts non-HTTP protocols, Cloudflare’s proxy is not in that path anyway and this article’s header logic does not apply. And if the “LB” is a single Nginx doing TLS for one backend, you have a reverse proxy, not a balancing tier — simpler rules apply.

Common mistakes

  • Trusting CF-Connecting-IP from any TCP peer. Without the ACL or set_real_ip_from gate, anyone reaching the LB directly can spoof any client IP — which then flows into your rate limits and audit logs as fact.
  • Restoring the real IP at the LB but not forwarding it, so the LB logs are right and every backend still sees the LB address.
  • Health-checking through Cloudflare only. A green public check plus a dead LB is a contradiction you only notice during the outage.
  • LB idle timeout below ~100 seconds, producing intermittent 520s that get blamed on Cloudflare.
  • Letting the HAProxy trust list and the firewall allowlist drift apart — two copies of the same ranges, refreshed by two different jobs, one of them forgotten.

Prevention / maintenance checklist

  • One refresh job produces the Cloudflare range list; firewall, Nginx realip config, and HAProxy ACL file all consume that single artifact.
  • Timeout ordering documented next to the LB config, with the three numbers and why.
  • External LB health probe alerting independently of Cloudflare-path checks.
  • 502/520 rate on the LB graphed; a step change is a timeout or reuse regression.
  • Quarterly: re-run the direct-reachability test and re-diff the trust lists against developers.cloudflare.com/fundamentals/ guidance.

A Cloudflare migration with a written rollback plan, or a zone that gets reviewed quarterly instead of drifting — that is the operating discipline Stack Harbor sells under Managed Cloud Ops; book an infrastructure review.