Keeping my self-hosted Forgejo public against AI crawlers, with only Caddy
· 17 min read

Keeping my self-hosted Forgejo public against AI crawlers, with only Caddy

Table of Contents

My personal Forgejo instance was being crawled to death (like every other public forge). Thousands of home IPs, each asking for some file at some old commit and then disappearing, at 5 to 10 requests per second, on an old Intel Atom N2800 (2 cores / 4 threads, 1.86 GHz) with a spinning hard drive. This had the side effect of making my server really unresponsive at best, and fully broken at worst.

Spoiler: I didn’t make the forge private and I didn’t want to put Anubis or Cloudflare in front of it. All I did was add a couple of lines of Caddy config, which now block anonymous requests for the expensive pages before Forgejo even hears about them, and Forgejo went from 118 % CPU to its normal 0.3 %.

Caddy logo

Caddy is a web server and reverse proxy (similar to Nginx or Apache HTTPd) written in Go: it sits in front of your services, receives every request from the internet and forwards each one to the right container.

Its big selling point is its automatic HTTPS (it fetches and renews the TLS certificates by itself), and its config file, the Caddyfile, is short, readable and super simple to use: a site is a domain name followed by a block of directives like reverse_proxy localhost:3000.

Every trick in this post is a few lines of it.

My forge, my tiny server

The forge is my personal and public backup.

Most of my work lives on GitHub, but GitHub isn’t a place I control and things can vanish one day. There are also some projects I don’t want to share at all (like the git backup of my Obsidian vault, some fun personal projects, etc). So everything gets a copy on my own Forgejo: current projects, old ones, code snippets for this blog, mirrors of the projects I work on. It’s a personal forge that basically no one but me uses. I’m also a self-hosting addict, so I had to, you know 🤷

One important thing there is that I do want it public. Anyone should be able to read and clone the open stuff. Account creation is closed, so “public” means browsing and cloning, nothing more.

It runs on a small rented bare-metal server at OVH, which hosts a small dozen Docker containers (such as my OpenCloud with its Radicale calendar, a mail archive, an RSS reader, a CI runner…):

CPUIntel Atom N2800, 2 cores / 4 threads @ 1.86 GHz
RAM1.9 GB
Storagespinning hard drive
OSDebian 13 (trixie), everything in Docker Compose
Reverse proxyCaddy, installed on the host
Forgejov15, container capped at 512 MB of RAM

I noticed my server was struggling because OpenCloud and Radicale synchronisation kept breaking, and the whole machine sat under a huge constant load. My Beszel monitoring sums it up like this:

Beszel dashboard over 30 days: system CPU with spikes up to about 50 % from mid-October to November 2, then flat at a few percent; Docker CPU shows Forgejo using 40 % of the 42 % total on October 31
30 days of Beszel. The holes in the Docker graphs aren't missing data from my side: the server was so busy it couldn't even report to Beszel 😅

That’s a 30-day average view, so the real peaks were worse (100%). On October 31 at 19:30 (while it was buried under bots), Forgejo alone was using 40 % of the 42 % total container CPU. Then, from November 3 on (once I finished blocking everything), flat.

What I wanted:

  1. The forge stays public
  2. The server (and the other services) stop dying
    • This means mainly blocking the bot traffic on my Forgejo
  3. A set-and-forget fix, as simple as possible. I’m not trying to be original with that fix, I just don’t want to babysit any of it.

Idea 1: just cap the CPU

First reflex: Forgejo is hogging the CPU, so cap it. Docker Compose has a cpus key for that:

services:
  forgejo:
    image: codeberg.org/forgejo/forgejo:15
    # ...
    cpus: 2   # at most 2 of the 4 threads
    mem_limit: 512m # also limit the RAM usage
    memswap_limit: 1g # also allow swapping, even though it's stupid on an HDD

docker stats just before:

NAME               CPU %     MEM USAGE / LIMIT     MEM %
docker-forgejo-1   118.63%   416.1MiB / 512MiB     81.28%

My server is responsive again, but this isn’t fixing the flooding problem. All it does is give the service an infinite queue, and everything on my server is just slower to answer (making it bad to use for me too in the meantime).

So I went to look at what the flood was and how to stop it.

What the logs said

[...]
GET /gama-platform/gama/raw/commit/fc892d7a.../gama.core/src/gama/core/runtime/IExperimentStateListener.java for 72.63.x.x, 200 OK in 246.2ms
GET /gama-platform/gama/src/commit/7a960bc0.../gama.ui.shared/src/gama/ui/shared for 45.112.x.x, 200 OK in 562.8ms
GET /gama-platform/gama/commits/commit/5a6b3a01.../gama.parent/.settings/org.eclipse.core.resources.prefs for 142.162.x.x, 200 OK in 327.8ms
GET /gama-platform/gama/blame/commit/092c3973.../gama.extension.fipa/.classpath for 50.4.x.x, 200 OK in 225.3ms
GET /gama-platform/gama/src/commit/f0c691e1.../gama.core/src/gama/gaml/operators/Dates.java for 197.18.x.x, 200 OK in 2279.6ms
[...]

Most of the logs will be trimmed: commit hashes shortened (nothing interesting there), and the last two octets of each IP hidden, since these are random people’s home connections and I don’t want to list them.

Each line has a different IP and asks for a single file at a specific commit: the file view (src/commit), the raw file (raw/commit), its history (commits/commit) or its blame (who wrote each line, blame/commit). Each of those makes Forgejo run git operations, between 150 ms and 2 s of CPU on this machine. And it almost always hits gama-platform/*: my mirrors of the GAMA platform, a big Java project with years of history. For a crawler, thousands of commits times thousands of files is a practically infinite list of URLs.

Banning IPs was pointless: they rotate on every request. That’s a residential proxy network: the scraper rents bandwidth on ordinary home and mobile connections, so its traffic looks like regular people1.

The quick fix was to set, within Forgejo, the GAMA organisation to “limited” (the organisation and its repo are only visible to logged-in users), and the load dropped (almost) right away. But it also hid exactly what I wanted to keep public, and since I’m the only user on the forge, nobody could see those projects anymore.

Since each crawler request comes from a different IP, I figured they don’t keep any state (some one-shot requests fetching pages with curl commands or such).

So the idea is: block the commit-pinned paths in Caddy, and let a request through only if it carries a custom cookie. Without one, Caddy answers with a tiny page that sets the cookie and reloads itself to redirect to the requested page. A browser goes through in a blink, a (bad) script never would.

My first version was simpler/dumber and simply returned a 403 on those paths. But I did it like an ass and I immediately locked myself out 😂

When you open a file from a commit (even the latest one), Forgejo links to it through /src/commit/<sha>/…. Hence the cookie version:

# My reverse-proxied forge URL, please don't crawl
git.arthurbrugiere.fr {
	# Heavy page and no cookie? Set one and reload
	@pinned_nocookie {
		path_regexp ^/[^/]+/[^/]+/(src|raw|blame|commits)/commit/
		not header Cookie *caddy_human=1*
	}

	handle @pinned_nocookie {
		header {
			Set-Cookie "caddy_human=1; Path=/; Max-Age=2592000; Secure; HttpOnly; SameSite=Lax"
			Content-Type "text/html; charset=utf-8"
			Cache-Control "no-store"
		}
		respond `<!doctype html><meta http-equiv="refresh" content="0"><p>Loading…</p>` 200
	}

	# Everything else goes to Forgejo
	handle {
		reverse_proxy localhost:3000
	}
}

I set the organisation public again, and the bot traffic showed up within seconds… Crap…

A fatty forge

Actually, I noticed something even worse in the logs:

GET /gama-platform/gama.old/archive/f2618e4c...:ummisco.gama.ui.modeling.tar.gz for 88.177.x.x, 200 OK in 2108.2ms
GET /gama-platform/gama.experimental/archive/GAMA_1.9.0:ummisco.gama.extension.hecras/models/GAMA%20to%20hecras/Phuc%20Xa%20Simulation.zip for 47.82.x.x, elapsed 3991.6ms
GET /gama-platform/gama.old/rss/branch/GAMA_MPI/msi.gama.models/models/Toy%20Models/Comodels/.project for 47.79.x.x, 200 OK in 2130.2ms

That’s Forgejo building a tarball of one sub-folder at one commit (2 to 4 seconds each) plus RSS feeds of single files on old branches. The archives also get cached on disk:

$ du -sh ./forgejo/gitea/repo-archive
2.7G    ./forgejo/gitea/repo-archive

2.7 GB of tarballs nobody will ever download, sitting on my tired HDD. I purged them from Site Administration -> Maintenance operations (back down to 9.5 MB), then extended the regex to every expensive page type I could think of: src|raw|blame|commits|commit|archive|rss|atom|compare|graph|activity.

Not your usual script kiddie

It held for a few hours. Then:

GET /favicon.ico for 104.165.x.x, 301 Moved Permanently in 0.1ms
GET /gama-platform/gama/src/commit/ee250296.../gama.feature.devtools/build.properties for 104.165.x.x, 200 OK in 228.4ms
GET /favicon.ico for 104.165.x.x, 301 Moved Permanently in 0.1ms
GET /gama-platform/gama/blame/commit/b6030ce2.../gama.core/src/gama/core/util/IReference.java for 104.165.x.x, 200 OK in 462.5ms

The interesting part is the /favicon.ico being fetched before each page.

Scripts don’t fetch favicons, that’s a browser thing. These bots run a real headless browser (Chrome without a window), which happily stores my cookie, follows my refresh and gets past whatever simple system I set up to block one-shot fetches. Each request gets a fresh browser on a fresh home IP, and from Caddy’s point of view it’s a human visitor like any other. The cookie trick only filters the dumb scrapers.

Idea 3: a slow queue of requests

If I can’t tell the bots apart, maybe I can at least limit how many expensive pages Forgejo builds at the same time and make my forge less interesting to crawl. Caddy’s reverse_proxy can cap its connections to the backend (max_conns_per_host 2), and extra requests wait in a queue. That would keep the CPU in check, sure.

However, the bots send at least 5 requests per second, Forgejo can answer maybe 2 to 6 per second, so the queue only ever grows. A real visitor would sit at the end of it behind hundreds/thousands of bot requests, and never get the page. Rejecting the extra requests instead of queuing them isn’t better: a human would just get the same “busy” odds as a bot.

Idea 4: logged in or nothing

That leaves one thing the bots can’t fake: an account on my forge. Gitea (the project Forgejo forked from) has a REQUIRE_SIGNIN_VIEW = expensive setting for exactly this, which keeps the expensive pages for logged-in users. As far as I could find, Forgejo doesn’t have it as of November 2026, so let’s do it by hand!

Asking Forgejo who’s logged in

The trick comes from tusooa’s post on the same crawlers: ask Forgejo for a cheap page that needs a login. /user/settings returns 200 if you’re logged in and a 303 redirect to the login page if not. Caddy’s forward_auth does exactly that: before proxying a request, it sends a copy to another URL (with the same visitor identity, i.e. cookies) and only continues on a 2xx. Anything else goes straight back to the client:

	# Long list of all the expensive pages
	@heavy path_regexp ^/[^/]+/[^/]+/(src/commit|src/tag|raw/commit|blame|commits|commit|archive|rss|atom|compare|graph|activity)(/|$)
	handle @heavy {
		# Logged in? /user/settings answers 200 and we carry on.
		# Not logged in? Its 303 to the login page goes to the client.
		forward_auth localhost:3000 {
			uri /user/settings
		}
		reverse_proxy localhost:3000
	}

The cookie code is replaced by this one.

src/branch and raw/branch aren’t in the list as I do want anyone to be able to browse every project at its current state, or on the repo’s branches.

The logs right after:

GET /user/settings for 189.81.x.x, 303 See Other in 0.6ms
GET /favicon.ico for 189.81.x.x, 301 Moved Permanently in 0.1ms
GET /user/login for 189.81.x.x, 200 OK in 12.0ms

What it means: the /user/settings line is Caddy’s check (logged with the bot’s IP), then the bot’s browser follows the redirect to the login page and grabs the favicon on the way. About 13 ms per bot request, instead of 200 to 4,000 ms of CPU work.

Not even asking Forgejo

13 ms at 10 requests per second is fine, but it still meant work on my machine. So I looked at what cookies Forgejo sets for an anonymous visitor:

$ curl -sI https://git.arthurbrugiere.fr/ | grep -i set-cookie
$

Nothing. Forgejo only gives you a session cookie once you log in. This means that a request without one can’t come from a logged-in user, so Caddy can identify them without asking Forgejo and answer them alone, with a small 401 page and a login link that brings you back to the file you wanted:

	@heavy_anonymous {
		path_regexp ^/[^/]+/[^/]+/(src/commit|src/tag|raw/commit|blame|commits|commit|archive|rss|atom|compare|graph|activity)(/|$)
		# Forgejo's session cookie, and the "remember me" one
		not header_regexp Cookie (i_like_gitea|gitea_incredible)=
	}
	handle @heavy_anonymous {
		header Content-Type "text/html; charset=utf-8"
		respond `<!doctype html><title>Login required</title><p>History, blame and archives are only available to logged-in users. <a href="/user/login?redirect_to={http.request.uri.path}">Log in</a> or clone the repository.</p>` 401
	}

It goes before handle @heavy, which stays for anyone carrying a cookie: if a bot ever forges one, it falls back to the login check and still gets nothing. The cookie names are Forgejo’s defaults2; check yours in your browser’s dev tools while logged in.

Since then, nearly all the bot traffic Forgejo sees is the favicon their browsers fetch after reading my 401 page, 0.1 ms each. A trickle of old-branch file views remains (src/branch/GAMA_1.8.1/…, about one a minute at 100 to 300 ms), which is the swarm finishing whatever URLs it can still reach. If it ever grows, src/branch can join the regex.

The extras I added anyway

Two more things went in along the way. Neither did anything against the residential swarm, but they’re cheap:

  • An IP blocklist for the big cloud providers. Part of the traffic (all the 47.79.x and 47.82.x) came from Alibaba Cloud, and some from Tencent and Huawei Cloud. Those are servers in datacenters, not people, which are easy to identify. A small Python script asks RIPEstat for the IP ranges each provider announces and writes them as a Caddy snippet, automatically refreshed weekly by cron.
  • The ai.robots.txt Caddy snippet, which drops requests whose User-Agent says GPTBot, ClaudeBot, Bytespider and friends. It only catches the honest bots saying who they are, and the list contains plain words like Code or Spider, so some legit tools may get caught too3.

Both are snippets, and you need to pay attention to two things to use them well (I made those mistakes):

First, import blocklist.caddy at the top of the Caddyfile only defines the snippet; each site also needs its own import block_scrapers.

Second, Caddy runs abort after all handle blocks, so a bare abort @aibots never fires in a site where everything is answered by a handle. Wrap it in handle @aibots { abort } and import the snippets first in the site block, since handle blocks with named matchers run in the order they’re written.

Testing that the abort works (it looks like an error, which is the point):

$ curl -A GPTBot https://git.arthurbrugiere.fr/
curl: (92) HTTP/2 stream 1 was not closed cleanly: INTERNAL_ERROR (err 2)
The blocklist script
#!/usr/bin/env python3
# Usage: python3 update-blocklist.py /etc/caddy/blocklist.caddy
# If a lookup fails, the existing file is left untouched.
import ipaddress, json, sys, urllib.request

ASNS = {
    45102: "Alibaba Cloud (international)",
    37963: "Alibaba Cloud (China)",
    132203: "Tencent Cloud (international)",
    45090: "Tencent Cloud (China)",
    136907: "Huawei Cloud (APAC)",
    55990: "Huawei Cloud (China)",
    396986: "ByteDance",
    # Add whatever you want to block here
}
URL = "https://stat.ripe.net/data/announced-prefixes/data.json?resource=AS{}&sourceapp=caddy-blocklist"

def prefixes(asn):
    req = urllib.request.Request(URL.format(asn), headers={"User-Agent": "caddy-blocklist/1.0"})
    with urllib.request.urlopen(req, timeout=60) as r:
        return [p["prefix"] for p in json.load(r)["data"]["prefixes"]]

v4, v6 = [], []
try:
    for asn in ASNS:
        for p in prefixes(asn):
            net = ipaddress.ip_network(p, strict=False)
            (v4 if net.version == 4 else v6).append(net)
except Exception as e:
    sys.exit(f"Lookup failed, keeping the old blocklist: {e}")

nets = [str(n) for n in ipaddress.collapse_addresses(v4)] + [str(n) for n in ipaddress.collapse_addresses(v6)]
lines = ["(block_scrapers) {", "\t@scraper_dc {"]
lines += ["\t\tclient_ip " + " ".join(nets[i:i + 40]) for i in range(0, len(nets), 40)]
lines += ["\t}", "\thandle @scraper_dc {", "\t\tabort", "\t}", "}", ""]
with open(sys.argv[1], "w") as f:   # written in place, so a bind mount keeps working
    f.write("\n".join(lines))

And the weekly cron:

0 4 * * 1  python3 /etc/caddy/update-blocklist.py /etc/caddy/blocklist.caddy && systemctl reload caddy

The final config

Here’s the final Forgejo site block that I’m using:

import blocklist.caddy   # defines (block_scrapers)

git.arthurbrugiere.fr {
	import block_scrapers   # cloud IP ranges, dropped
	import block_aibots     # declared AI User-Agents, dropped

	# Proactively block visits without any cookie on heavy pages
	@heavy_anonymous {
		path_regexp ^/[^/]+/[^/]+/(src/commit|src/tag|raw/commit|blame|commits|commit|archive|rss|atom|compare|graph|activity)(/|$)
		not header_regexp Cookie (i_like_gitea|gitea_incredible)=
	}
	handle @heavy_anonymous {
		header Content-Type "text/html; charset=utf-8"
		respond `<!doctype html><title>Login required</title><p>History, blame and archives are only available to logged-in users. <a href="/user/login?redirect_to={http.request.uri.path}">Log in</a> or clone the repository.</p>` 401
	}

	# Check if user with cookie is logged in on heavy pages
	@heavy path_regexp ^/[^/]+/[^/]+/(src/commit|src/tag|raw/commit|blame|commits|commit|archive|rss|atom|compare|graph|activity)(/|$)
	handle @heavy {
		forward_auth localhost:3000 {
			uri /user/settings
		}
		reverse_proxy localhost:3000
	}

	# Reverse Forgejo normally for the other pages
	handle {
		reverse_proxy localhost:3000
	}
}

What it means for visitors:

Anonymous visitor (or bot)Logged in
Repo home, README, issues, PRs, releases✅✅
Files on a branch (src/branch/main/…)✅✅
git clone over HTTPS or SSH✅✅
Files at a commit, blame, history, diffs401 page✅
Archives (.zip/.tar.gz), RSS feeds, graph401 page✅

The main inconvenience is that an anonymous visitor can’t dig into the history in the browser. It’s still a minor one since, again, most projects are mirrors: anyone can still clone the repo and run git log like a grown-up, and release attachments are still downloadable. I can live with that drawback.

And the container’s stats:

BeforeAfter
Forgejo CPU (docker stats)118.63 %0.32 %
Forgejo RAM416 MiB / 512 MiB274 MiB
System CPU (Beszel, 30-day average)peaks around 50 %a few %
Cached archives on disk2.7 GB9.5 MB
Cost of one bot request150 to 4,000 ms of git worknothing, Caddy answers

Why not Anubis, then? It’s great, and it’s probably the right answer for a forge with real users (it’s been made for that exact use case!). I wanted to see how far I could go without it, and I don’t want a proof-of-work loading screen between me and my own stuff (a challenge that is pretty cheap for a datacenter to solve anyway). I’m tired of seeing it everywhere and waiting several seconds for every page4.

Bref, the load has been flat for weeks and nothing is trying to walk through each file of each commit of my forge anymore. It’s still public, I didn’t install anything new, and the swarm now spends its headless Chromes reading a one-line HTML page 😁

Footnotes

  1. From what I read, that bandwidth usually comes from SDKs bundled into free apps, whose users don’t really know their connection is being rented out. Not something you can fix from a Caddyfile. ↩

  2. If one of your tools suddenly stops reaching your sites, look at that list first. ↩

  3. Anubis can let some IP ranges skip the challenge with an ALLOW rule. I didn’t look into it, I don’t care 🙃 ↩

This post is licensed under CC BY 4.0.