The User-Agent trap

Two failure modes, one cause. Either the rule matches the header and a scraper changes one string to walk through it, or the rule is written slightly wrong and it blocks the real crawler — after which your indexing quietly collapses and nobody notices for three weeks.

# Do not do this
if ($http_user_agent ~* "Googlebot") {
    return 403;
}

This blocks Googlebot itself as readily as the impostor, and it cannot tell the two apart because it never looks at the network. Blocking has to start from something the client cannot type.

The shape of a working policy

Three layers, each doing one job:

  1. Verified allow-list. Addresses inside the operator's published ranges get a marker. They skip the rate limiter and never see a challenge.
  2. Rate limit for everyone else. Not a block — a budget. Legitimate readers and small crawlers stay under it; a scraper pulling 40 pages a second does not.
  3. Hard block only for the confirmed-bad. Addresses caught spoofing a verified bot, or repeatedly hammering after a 429.

This is deliberately not "block all bots". A blocklist of scraper IPs is stale the moment it is written; a rate limit is a property of behaviour and keeps working.

Nginx: ranges, real IP and rate limits

Start with the ranges. geo builds the lookup at config load, so it costs nothing per request:

# /etc/nginx/conf.d/verified-bots.conf
geo $verified_crawler {
    default 0;
    include /etc/nginx/snippets/googlebot-ranges.conf;
    include /etc/nginx/snippets/bingbot-ranges.conf;
    include /etc/nginx/snippets/openai-ranges.conf;
}

map $verified_crawler $limit_key {
    1       "";                 # empty key = no limit applied
    default $binary_remote_addr;
}

limit_req_zone $limit_key zone=crawlers:10m rate=60r/m;

server {
    # ...
    location / {
        limit_req zone=crawlers burst=20 nodelay;
        limit_req_status 429;
        proxy_pass http://127.0.0.1:3004;
    }
}

and each include file is a plain list:

# /etc/nginx/snippets/googlebot-ranges.conf
66.249.64.0/27   1;
66.249.64.32/27  1;
# ... one line per prefix

If you sit behind Cloudflare, the socket address is Cloudflare's. Restore the real client first, or every visitor shares one rate-limit bucket:

# /etc/nginx/conf.d/cloudflare-realip.conf
# Only valid when traffic actually arrives through Cloudflare.
real_ip_header CF-Connecting-IP;
set_real_ip_from 173.245.48.0/20;
set_real_ip_from 103.21.244.0/22;
set_real_ip_from 104.16.0.0/13;
set_real_ip_from 172.64.0.0/13;
set_real_ip_from 162.158.0.0/15;
set_real_ip_from 198.41.128.0/17;
set_real_ip_from 2400:cb00::/32;
set_real_ip_from 2606:4700::/32;
Order matters

real_ip must run before the rate limiter sees the address. Put the realip include at the http level, not inside a location block, and check $remote_addr in the access log afterwards.

Generating the allow-list from the JSON

Do not paste ranges by hand — they change. This script rewrites the include file from the live feeds and reloads nginx only if something changed:

#!/usr/bin/env bash
# refresh-ranges.sh — run from cron every six hours
set -euo pipefail
OUT=/etc/nginx/snippets/googlebot-ranges.conf
TMP=$(mktemp)

for feed in googlebot special-crawlers user-triggered-fetchers; do
  curl -fsS --max-time 20 \
    "https://developers.google.com/static/search/apis/ipranges/${feed}.json" \
    | python3 -c '
import json, sys
doc = json.load(sys.stdin)
for p in doc["prefixes"]:
    prefix = p.get("ipv4Prefix") or p.get("ipv6Prefix")
    if prefix:
        print(prefix, 1, sep="\t")
' >> "$TMP" || echo "warn: $feed fetch failed" >&2
done

sort -u "$TMP" | sed 's/\t/    /' > "$OUT.new"
if ! cmp -s "$OUT" "$OUT.new"; then
  mv "$OUT.new" "$OUT"
  nginx -t && systemctl reload nginx
else
  rm -f "$OUT.new"
fi
rm -f "$TMP"

Make it idempotent and it becomes a five-minute job that never needs attention again. The same pattern works for Bingbot (https://www.bing.com/toolbox/bingbot.json) and OpenAI (https://openai.com/gptbot.json, searchbot.json, chatgpt-user.json).

If you want the forward-confirmed DNS check too, do it in application middleware rather than in nginx — a DNS lookup on every request in the request path is a latency trap. Cache the result per address for an hour and it becomes cheap.

Cloudflare: verified bots and WAF rules

Cloudflare already verifies major crawlers against the same published ranges and exposes the result as a field. Use it instead of rebuilding it:

  • cf.client.bot — true for traffic Cloudflare has verified as a known bot. It is evidence, not decoration: it is computed from the connection, not the header.
  • Verified Bots in Security → Bots lets you allow that category in one rule and keep everything else under a challenge.
  • WAF custom rules handle the specific case — for example a rule that challenges any request claiming a bot User-Agent without cf.client.bot being true.

A rule set that does the job without collateral damage:

PriorityExpressionAction
1cf.client.botSkip remaining rules
2http.user_agent contains "Googlebot" and not cf.client.botBlock
3http.user_agent contains "GPTBot" and not cf.client.botBlock
4Rate limit: 100 requests / minute per IP on HTMLManaged challenge

Rule 2 is the important one: it converts "claims to be Google" into a hard fail unless Cloudflare's own verification agrees. It is the cheapest spoofed-Googlebot filter available, and it cannot block the real crawler because the real crawler is verified on connect.

One caveat: if you block AI crawlers by User-Agent at the edge, you also block the honest ones. Prefer robots.txt for policy and reserve the WAF for spoofing and abuse. The distinction is intent: robots.txt says "you may not"; a WAF says "you cannot".

Testing it without breaking production

Before reloading, prove both directions:

# 1. A spoofed Googlebot from a non-Google address must fail.
curl -s -o /dev/null -w '%{http_code}\n' \
  -A 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)' \
  https://example.com/

# 2. The real range must still pass (run from inside the allow-list or trust the log).
#    Easier: check that the geo lookup resolves the addresses you expect.
nginx -T | grep -A2 'geo \$verified_crawler'

# 3. Confirm the rate limiter keys on the client, not the proxy.
tail -f /var/log/nginx/access.log   # $remote_addr should be the visitor, not 172.x

Then watch the two numbers that tell you whether you got it right: 429 rate in the log (should be small and concentrated on a few addresses) and Search Console crawl stats (should not fall off a cliff). A sudden drop in crawl requests after a deploy is almost always an accidental block of a verified crawler.

If you want to check an address before it lands in production, the verifier runs the same range and DNS logic and tells you which signal decided it.