---

title: Sites behind Cloudflare
description: Run knownprint's nginx proxy rule behind Cloudflare's proxied DNS, with the visitor's real address, and set Cloudflare so the /kp/ paths are neither cached wrongly nor altered.
---

This page is for a site whose DNS Cloudflare proxies (the orange cloud) in front of an nginx server. Browsers then connect to Cloudflare, and Cloudflare connects to your server. Two things need care:

- **The visitor's address.** Your server sees Cloudflare's address on every connection. The Cloudflare variant of the nginx recipe takes the visitor's address from the header Cloudflare adds, and only on connections that come from Cloudflare.
- **Cloudflare's own features.** Caching, script optimisation, header rewriting and security challenges must leave the `/kp/` paths as your server answers them.

If your DNS record is not proxied (DNS only, the grey cloud), Cloudflare is not in the path: use the plain recipe on [Install on nginx](/install/nginx) and skip this page.

## The Cloudflare variant

The nginx files from your account include `knownprint-cloudflare.conf`. It is `knownprint.conf` with two additions, and you include it in your `server` block in its place:

1. `real_ip_header CF-Connecting-IP;` tells nginx to take the client address from the `CF-Connecting-IP` header, which Cloudflare sets to the visitor's address.
2. One `set_real_ip_from` line for each of Cloudflare's published address ranges, between the comment lines `# CLOUDFLARE_RANGES:` and `# CLOUDFLARE_RANGES end`. nginx reads the header only on connections from those ranges.

What this changes for you:

- On a connection from Cloudflare, nginx's `$remote_addr` becomes the visitor's address, and the rule passes that address to knownprint with your proxy secret. Events show the visitor's address in `network.ip`, not a Cloudflare server's.
- The setting applies to the whole `server` block, not only to `/kp/`: your access log and anything else that reads `$remote_addr` in that block see the visitor's address too.
- A request that reaches your server directly, not through Cloudflare, keeps the address of its own connection. Nobody can claim another address by sending the header themselves.
- The variant needs nginx's real IP module (`ngx_http_realip_module`). Most distribution packages and the packages from nginx.org include it.

The ranges only work when nginx receives connections straight from Cloudflare. If a load balancer of your own sits between Cloudflare and nginx, connections come from the load balancer and the header is not read: talk to your knownprint contact before you go live with that setup.

The Caddy snippet has no Cloudflare variant: it passes the address of the connection Caddy accepted, which behind Cloudflare's proxy is a Cloudflare server. Use nginx for a site behind Cloudflare, or talk to your knownprint contact first.

## Install

Follow [Install on nginx](/install/nginx) from step 1 to step 8, with two differences:

- In [step 1](/install/nginx#step-1-copy-the-files), copy `knownprint-cloudflare.conf` into `/etc/knownprint/` beside the other files.
- In [step 5](/install/nginx#step-5-include-the-recipe-in-your-site-s-server-block), include the variant instead of `knownprint.conf`:

```nginx title="/etc/nginx/sites-available/www.example.com"
server {
    listen 443 ssl;
    listen [::]:443 ssl;
    server_name www.example.com;

    ssl_certificate     /etc/ssl/www.example.com/fullchain.pem;
    ssl_certificate_key /etc/ssl/www.example.com/privkey.pem;

    include /etc/knownprint/knownprint-cloudflare.conf;

    # Your site. Pass the visitor's address and scheme on to your application.
    location / {
        proxy_pass http://localhost:3000;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}
```

The variant makes `$remote_addr` the visitor's address, so the last entry nginx appends to `X-Forwarded-For` is the visitor's, which is the entry your backend compares with `network.ip` ([The visitor address](/install/server#the-visitor-address)).

The map file in the `http` block, the proxy secret file and the disclosure file are the same as for the plain recipe.

If this `server` block already has `real_ip_header` or `set_real_ip_from` lines of its own for Cloudflare, remove them: the variant sets both, and nginx refuses `real_ip_header` twice in one block. Lines of that kind at the `http` level do not conflict; for this `server` block, the variant's lines are the ones that apply.

## Keep Cloudflare's ranges current

Cloudflare publishes its ranges at `https://www.cloudflare.com/ips-v4` and `https://www.cloudflare.com/ips-v6` and changes them from time to time. `nginx -t` checks the syntax of the block, not whether the ranges are current. With an outdated list, visitors who reach you through a new Cloudflare range are recorded under Cloudflare's address.

This script rewrites the block between the two comment lines from Cloudflare's lists, tests the configuration, reloads nginx, and puts the previous file back if the test fails. It changes no other line of the file:

```bash title="/usr/local/sbin/knownprint-cloudflare-ranges"
#!/bin/sh
# Rewrites the CLOUDFLARE_RANGES block of the Cloudflare variant from
# Cloudflare's published lists, then tests and reloads nginx.
set -eu
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
export PATH

conf=${1:-/etc/knownprint/knownprint-cloudflare.conf}
fetched=$(mktemp)
ranges=$(mktemp)
trap 'rm -f "$fetched" "$ranges"' EXIT

curl -fsS https://www.cloudflare.com/ips-v4 > "$fetched"
echo >> "$fetched"
curl -fsS https://www.cloudflare.com/ips-v6 >> "$fetched"
echo >> "$fetched"

awk '$1 ~ /^[0-9A-Fa-f:.]+\/[0-9]+$/ { print "set_real_ip_from " $1 ";" }' "$fetched" > "$ranges"
if [ "$(wc -l < "$ranges")" -lt 10 ]; then
  echo "too few ranges fetched; $conf left unchanged" >&2
  exit 1
fi

cp -p "$conf" "$conf.bak"
awk -v ranges="$ranges" '
  /^# CLOUDFLARE_RANGES:/ { inblock = 1 }
  /^# CLOUDFLARE_RANGES end/ {
    while ((getline line < ranges) > 0) print line
    inblock = 0
  }
  inblock && /^set_real_ip_from / { next }
  { print }
' "$conf.bak" > "$conf"

if nginx -t; then
  systemctl reload nginx
else
  cp -p "$conf.bak" "$conf"
  echo "nginx -t failed; the previous ranges are restored" >&2
  exit 1
fi
```

Install it and run it once as root, then schedule it, for example weekly:

```bash
sudo install -m 0755 knownprint-cloudflare-ranges /usr/local/sbin/knownprint-cloudflare-ranges
sudo /usr/local/sbin/knownprint-cloudflare-ranges
echo '17 4 * * 1 root /usr/local/sbin/knownprint-cloudflare-ranges' | sudo tee /etc/cron.d/knownprint-cloudflare-ranges
```

When knownprint sends you a new version of `knownprint-cloudflare.conf`, install it and run the script once, so the new file gets the current ranges.

## What to set in Cloudflare

Cloudflare follows the cache headers your server sends unless a setting or rule overrides them. Out of the box it caches the loader at its edge for the minute the rule allows and the script files for up to the year they allow, and never caches the identification requests. The settings below keep it that way and keep the answers intact.

| Setting                                                                               | Set it to                                                                                      | Why                                                                                                                                                                                                                                                                                                                                        |
| ------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| DNS record of the site                                                                | Proxied                                                                                        | The variant is for proxied DNS. With DNS only, use the plain recipe.                                                                                                                                                                                                                                                                       |
| SSL/TLS encryption mode                                                               | Full (strict)                                                                                  | The rule lives in your server's TLS `server` block. With Flexible, Cloudflare connects to your server over plain `http`, where the rule is not.                                                                                                                                                                                            |
| Cache Rules and Page Rules                                                            | None that match `/kp/` with "cache everything", an Edge TTL override or a Browser TTL override | The loader names the current release of the script files. Kept longer than the rule allows, it can ask for a release that is no longer served, and the script fails with `load_failed`.                                                                                                                                                    |
| Browser Cache TTL                                                                     | Respect Existing Headers                                                                       | A fixed value would override the loader's one-hour browser lifetime.                                                                                                                                                                                                                                                                       |
| Rocket Loader                                                                         | Off, or keep it off the loader's script tag                                                    | It changes how script tags on your pages run. To keep it on for the rest of the page, add `data-cfasync="false"` to the tag that loads `/kp/agent.js`.                                                                                                                                                                                     |
| Pseudo IPv4                                                                           | Off, or Add header                                                                             | "Overwrite headers" replaces the address in `CF-Connecting-IP` of IPv6 visitors with a made-up IPv4 address, which knownprint would then record.                                                                                                                                                                                           |
| Managed Transforms                                                                    | "Remove visitor IP headers" off                                                                | It removes the header the variant reads the visitor's address from.                                                                                                                                                                                                                                                                        |
| Transform Rules, Snippets and Workers                                                 | None that change requests or answers under `/kp/`                                              | The rule needs the browser's headers and cookies as sent, and the browser needs knownprint's answers as sent, `Set-Cookie` included. The loader refuses script files that were altered on the way.                                                                                                                                         |
| Security challenges (I'm Under Attack mode, WAF rules that challenge, Bot Fight Mode) | Not applied to `/kp/`                                                                          | The script's requests cannot answer a challenge page, so a challenged request fails and the page gets no request id. Where your plan allows it, add a WAF custom rule that skips these features for requests whose URI path starts with `/kp/`. Bot Fight Mode cannot be skipped by a rule; if it challenges `/kp/` requests, turn it off. |

If a site-wide Cache Rule caches everything, add a Cache Rule for "URI Path starts with `/kp/`" set to Bypass cache, and order it after the site-wide rule so it takes precedence. The script files then come from your server on every request, which costs a little bandwidth and is otherwise harmless.

Your HTML pages may be cached by Cloudflare as before: the script identifies each visitor with its own requests, which are never cached.

## Check

Run the checks of [step 8](/install/nginx#step-8-check-with-curl) against your public hostname, through Cloudflare. Then look at what Cloudflare adds:

```bash
curl -sSI https://www.example.com/kp/agent.js
```

The answer carries a `cf-cache-status` header and `cache-control: public, max-age=3600, s-maxage=60`. A different `cache-control` means a Cloudflare setting overrides it.

```bash
curl -sS -D - -o /dev/null -X POST https://www.example.com/kp/c \
  -H 'Content-Type: application/json' -d '{}'
```

The answer is knownprint's `400` with `content-type: application/problem+json; charset=utf-8`. An HTML page with `403` or `503` instead means Cloudflare challenged the request: see the last row of the table above.

Finally, identify your own browser on a page of your site and read the event from your backend: `network.ip` must be the public address of the machine you browsed from. A Cloudflare address there means nginx did not take the visitor's address; see [Troubleshooting](#troubleshooting).

## Troubleshooting

| What you see                                                             | Cause                                                                                                                                               | Fix                                                                                         |
| ------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------- |
| Events show a Cloudflare address in `network.ip`                         | The `server` block includes `knownprint.conf` instead of the variant, the ranges are outdated, or a load balancer sits between Cloudflare and nginx | Include `knownprint-cloudflare.conf`, refresh the ranges, and check what connects to nginx. |
| Events from IPv6 visitors show IPv4 addresses that do not belong to them | Pseudo IPv4 is set to Overwrite headers                                                                                                             | Set it to Off or Add header.                                                                |
| Events show your server's address                                        | The proxy secret is wrong or of another environment                                                                                                 | Check the secret file ([step 2](/install/nginx#step-2-store-the-proxy-secret)) and reload.  |
| `nginx -t`: `"real_ip_header" directive is duplicate`                    | The `server` block already sets `real_ip_header`                                                                                                    | Remove the block's own line; the variant sets it.                                           |
| `nginx -t`: `unknown directive "real_ip_header"`                         | nginx was built without the real IP module                                                                                                          | Install a package that includes it.                                                         |
| `load()` rejects with `load_failed`                                      | A Cloudflare rule caches the loader too long, or a feature alters the script files                                                                  | Check the cache and transform settings in the table above.                                  |
| Requests to `/kp/c` or `/kp/i` answer with a Cloudflare HTML page        | A security challenge applies to `/kp/`                                                                                                              | Skip it for `/kp/` or turn the feature off.                                                 |
| Returning visitors are rarely recognised                                 | A Cloudflare rule or Worker removes `Set-Cookie` from `/kp/i` answers, or strips cookies from `/kp/` requests                                       | Remove the rule for `/kp/`.                                                                 |

The general troubleshooting table is on [Run knownprint from your domain](/install/proxy#troubleshooting), and the nginx configuration errors are on [Install on nginx](/install/nginx#troubleshooting).
