Caddy Warden: Caddyfile Reference
Comprehensive syntax and configuration options for Caddy Warden (github.com/routewarden/caddy-warden).
1. Directive Ordering
Caddy evaluates HTTP handler directives strictly according to an internal order. Custom third-party directives like routewarden (or route_warden) do not have a hardcoded position in Caddy's directive list. If placed alongside handlers like reverse_proxy without ordering, Caddy fails at startup with:
directive 'routewarden' is not an ordered HTTP handler, so it cannot be used here - try placing within a route block or using the order global optionTo resolve this, declare directive ordering in your Caddyfile's global options block:
{ # Recommended when site definitions use handle or handle_path order routewarden before handle}TIP
Using a route Block: Alternatively, select the Inside Route Block tab in the CodeViewer above. Encapsulating Routewarden and your upstream proxy inside a route { ... } block instructs Caddy to execute directives strictly in the order they are written, eliminating the need for global options.
IMPORTANT
Using handle or handle_path Blocks? In Caddy, handle blocks take routing priority over standard handlers. If your site blocks encapsulate reverse_proxy inside a handle block, use order routewarden before handle or wrap your site inside a route { ... } block to prevent requests from bypassing Routewarden. See the Caddy Warden FAQ for detailed examples.
2. Complete Caddyfile Schema
routewarden { # Load base config from a shared JSON file (inline fields override file values) config_file <path> # e.g. /etc/routewarden/routewarden.json # Boolean Flags enabled <true|false> # Default: true debug <true|false> # Default: false (verbose diagnostic logs) security_log <true|false> # Default: true (emit structured JSON audit events on stdout) enable_default_patterns <true|false> # Default: true (.env, .git, backups, keys, etc.) enable_default_allow_patterns <true|false> # Default: true (/robots.txt, /favicon.ico, etc.) check_query <true|false> # Default: false (inspect URI query strings) check_headers <headers...> # Optional: inspect forwarded headers (e.g. X-Forwarded-Uri X-Rewrite-URL) # Path Patterns to Block or Challenge (Go RE2 Regular Expressions) block_patterns <regex...> # Safe Whitelist Patterns (Overrides blocking) allow_patterns <regex...> # IP / CIDR Subnet Allowlist (Bypasses all checks) allowed_ips <ip_or_cidr...> # ASN Allowlist, Blocklist & Offline Routing DB allowed_asns <asns...> # e.g. AS13335 64500 (bare directive clears inherited) blocked_asns <asns...> # e.g. AS138699 (blocked crawler / proxy ASNs) asn_db <path> # e.g. /etc/routewarden/asn.json trusted_proxies <cidrs...> # Upstream proxies trusted for client IP resolution # AI Bot & Web Crawler Defense bot_defense_level <level> # e.g. standard (presets: off, light, standard, strict, aggressive) block_ai_bots <true|false> # Default: false (block known AI scrapers & LLM bots) ai_bot_profile <profile> # e.g. train_only (default), all, aggressive, custom block_user_agents <regex...> # Custom regex patterns matching User-Agents to block allow_user_agents <regex...> # Custom regex patterns matching User-Agents to allow detect_browser_impersonation <true|false> # Default: false (cross-check Client Hints and companion headers) block_script_clients <true|false> # Default: false (block automated HTTP clients & headless scrapers) verify_search_engine_bots <true|false> # Default: false (verify Googlebot/Bingbot/Applebot via FCrDNS) honeypot_trap_paths <paths...> # Decoy paths that trigger instant IP bans trap_ban_duration <duration> # Ban duration for trapped IPs (default: 24h) # HTTP Methods to Inspect (Default: GET) methods <methods...> # Response Actions response { mode <json|html|text|xml|redirect|captcha|silent_drop|gzip_bomb|tarpit|fake_success|ratelimit|proxy|infinite_stream|ai_poison|markov_tarpit|pow_challenge> status_code <int> body <string> redirect_url <url> proxy_url <url> gzip_bomb_mb <number> retry_after_seconds <int> tarpit_delay_ms <int> stream_size_mb <int> pow_difficulty <int> pow_secret <string> pow_timeout_seconds <int> captcha { provider <turnstile|hcaptcha|recaptcha> site_key <key> } }}3. Configuration Properties
| Directive | Type | Default | Description |
|---|---|---|---|
config_file | string | "" | Path to a routewarden.json file loaded as the base config. Inline Caddyfile fields take precedence over the file. |
enabled | bool | true | Enables or disables Routewarden inspection. |
debug | bool | false | Enables verbose diagnostic logging in Caddy's logger. |
security_log | bool | true | Emits single-line structured JSON security events on stdout for CrowdSec, SIEMs, or log aggregators on blocked requests. |
enable_default_patterns | bool | true | Blocks high-risk files (.env, .git, .aws, .ssh, .sql, .bak, etc.). |
enable_default_allow_patterns | bool | true | Whitelists standard files like /robots.txt, /favicon.ico, /sitemap.xml. |
check_query | bool | false | When enabled, also evaluates query parameters for sensitive file targets. |
block_patterns | list | [] | Additional regex patterns to intercept. |
allow_patterns | list | [] | Regex patterns that should always be allowed through. |
allowed_ips | list | [] | IPv4, IPv6, or CIDR blocks exempted from checks. |
allowed_asns | list | [] | Autonomous System Numbers (AS64500, 64500) allowed to bypass inspection. Bare allowed_asns clears inherited list. |
blocked_asns | list | [] | Autonomous System Numbers whose client IPs are blocked. Requires asn_db. |
asn_db | string | "" | Path to local JSON ASN routing snapshot database. |
bot_defense_level | string | "" | Preset bot defense level (off, light, standard, strict, aggressive). Activates pre-tuned bot defenses. |
block_ai_bots | bool | false | Enables automatic blocking of known AI crawlers and LLM training bots. |
ai_bot_profile | string | "" | AI bot profile: train_only (default), all, aggressive, or custom. |
block_user_agents | list | [] | Custom regex patterns matching client User-Agents to block. |
allow_user_agents | list | [] | Custom regex patterns matching client User-Agents to allow. |
detect_browser_impersonation | bool | false | Cross-validates browser User-Agents against Client Hints (Sec-CH-UA-Platform, Sec-CH-UA-Mobile, Sec-CH-UA brand integrity), Fetch Metadata (Sec-Fetch-*), and companion headers (Accept-Language, Accept-Encoding). |
block_script_clients | bool | false | Blocks automated HTTP client libraries (requests, Guzzle, reqwest, axios, curl) and headless framework headers (X-Playwright, X-Puppeteer, X-Cypress, Sec-WebDriver). |
verify_search_engine_bots | bool | false | Verifies Googlebot, Bingbot, and Applebot authenticity via FCrDNS. |
honeypot_trap_paths | list | [] | Hidden trap paths that trigger instant sliding-window IP bans. |
trap_ban_duration | string | "24h" | Ban duration for trapped IPs (e.g., 24h, 1h, 30m). |
trusted_proxies | list | [] | Trusted upstream reverse proxies / CIDRs for real client IP extraction. |
methods | list | ["GET"] | HTTP verbs to inspect (e.g. methods GET POST). Non-matching verbs bypass inspection. |
IMPORTANT
Inspecting Non-GET Methods (methods): By default, Routewarden only inspects GET requests (methods GET). If you are blocking API endpoints, authentication routes (e.g. POST /api/auth/login), or administrative actions that accept POST, PUT, DELETE, or PATCH, you must configure methods to include them (e.g. methods GET POST PUT DELETE PATCH HEAD). Unlisted HTTP verbs bypass Routewarden entirely and flow straight to the backend.
TIP
CrowdSec Integration: For automated attacker remediation using security_log, see the CrowdSec Integration Guide.
4. ASN Allowlisting (allowed_asns & asn_db)
Caddy Warden supports offline Autonomous System Number (ASN) based allowlisting using a local JSON routing snapshot:
example.com {
route {
routewarden {
allowed_asns AS13335 64500
asn_db /etc/routewarden/asn.json
trusted_proxies 10.0.0.0/8
response {
mode json
status_code 403
}
}
reverse_proxy backend:8080
}
}- Offline Snapshot: Generated using
python3 scripts/build-asn-db.pyfrom MaxMind GeoLite2/GeoIP2 ASN CSVs. - Clearing Inherited Lists: In multi-site setups where a base block configures
allowed_asns, specifying a bareallowed_asnswith no arguments in a child block explicitly clears any inherited ASN allowlist. - Anti-Spoofing: Header values like
CF-Connecting-ASNare never trusted; only the TCP socket address or sanitized IP fromtrusted_proxiesis matched. - For complete snapshot instructions and architecture details, see the ASN Filtering Guide.
5. Config File (config_file)
Instead of inlining every option in your Caddyfile, point Routewarden at a shared routewarden.json file. Inline Caddyfile fields always override file values, so you can keep a single shared policy file and customize per-site behaviour in the Caddyfile.
example.com { route { routewarden { config_file /etc/routewarden/routewarden.json # Override just the response mode for this site: mode tarpit } reverse_proxy backend:8080 }}The routewarden.json file uses the standard Routewarden JSON schema (view it with rwarden schema or the CLI Schema):
Merge Semantics
| Priority | Source |
|---|---|
| 1 (wins) | Inline Caddyfile / JSON API fields |
| 2 (base) | Fields from config_file |
- Empty/omitted Caddyfile directives defer to the file — you don't need to re-specify
block_patternsjust to changemode. - A missing or malformed file causes a hard startup error.
TIP
Mount routewarden.json as a Docker volume or Kubernetes ConfigMap and reference it from each virtual host's Caddyfile block for consistent policy across all services.
6. Built-in Default Patterns
Default Block Patterns (enable_default_patterns true)
When enabled (default), Caddy Warden intercepts requests matching these compiled regular expressions:
| Target Category | Compiled Regex | Intercepted Examples |
|---|---|---|
| Environment & Configs | (?i)(^|/)(\.env.|.\.(txt|log|bak|backup|sql|conf|config|ini|yaml|yml))$ | /.env, /.env.production, /app.config, /dump.sql, /debug.log, /app.ini |
| VCS & Hidden Metadata | (?i)(^|/)\.(git|svn|hg|bzr|cvs)(/.*|$) | /.git/config, /.git/HEAD, /.svn/entries |
| Cloud & Shell Credentials | (?i)(^|/)\.(aws|ssh|kube|docker)(/.*|$) | /.aws/credentials, /.ssh/id_rsa, /.kube/config |
| Archives & DB Dumps | (?i).*\.(tar|tar\.gz|tgz|zip|rar|7z|gz|bz2|iso|dump|sqlite|sqlite3|db)$ | /backup.tar.gz, /site.zip, /users.dump, /data.sqlite3 |
| Sensitive Admin & Metrics | (?i)(^|/)(phpinfo\.php|info\.php|server-status|server-info|actuator(/.*)?|metrics|heapdump|trace|env)$ | /phpinfo.php, /server-status, /actuator/health, /metrics |
| Package Managers & Locks | (?i)(^|/)(composer\.(json|lock)|package-lock\.json|yarn\.lock|pnpm-lock\.yaml|Pipfile|Pipfile\.lock|requirements\.txt)$ | /package-lock.json, /yarn.lock, /composer.lock, /requirements.txt |
Default Allow Patterns (enable_default_allow_patterns true)
When enabled (default), Caddy Warden immediately allows standard public resources through without checking block rules:
| Target Resource | Compiled Regex | Purpose |
|---|---|---|
| Crawler Indexing Directives | (?i)^/robots\.txt$ | Search engine bot crawling policy |
| Search Engine XML Sitemaps | (?i)^/sitemap.*\.xml$ | Public sitemaps (/sitemap.xml, /sitemap_index.xml) |
| Digital Ad Transparency | (?i)^/ads\.txt$ | Authorized digital advertising sellers verification |
| Security Disclosure Policies | (?i)^/security\.txt$ | RFC 9116 security researcher reporting endpoint |
| ACME & Web Standards | (?i)^/\.well-known(/.*)?$ | TLS certificate challenges & discovery (/.well-known/*) |
7. Response Modes Matrix
| Mode | Options | Typical Use Case |
|---|---|---|
json | status_code, body | REST API protection with clean JSON error |
html | status_code, body | Custom branded 404 or 403 error page |
text | status_code, body | Minimal plain-text rejection |
redirect | status_code, redirect_url | Deflect scanners to honeypot or warning page |
captcha | captcha.provider, captcha.site_key | Challenge suspicious visits via Cloudflare Turnstile/hCaptcha |
silent_drop | None | Reset TCP connection immediately (conn.Close()) |
gzip_bomb | status_code, gzip_bomb_mb | Active defense memory-exhaustion trap |
tarpit | tarpit_delay_ms | Slowloris defense trickling bytes to tie up scanner concurrency |
ratelimit | status_code, retry_after_seconds | 429 Too Many Requests response |
proxy | proxy_url | Transparent canary/forensics honeypot mirror |
fake_success | status_code, body | Synthetic decoy responses (wp-login, fake .env) |
ai_poison | None | Serves HTTP 200 with prompt injection directives & noai robots tag |
markov_tarpit | tarpit_delay_ms | Procedural word stream trickle to exhaust crawler context windows |
pow_challenge | pow_difficulty, pow_secret, pow_timeout_seconds | Cryptographic Proof-of-Work challenge solver (<2KB inline HTML/JS) returning HTTP 429 |
WARNING
silent_drop Behind Edge Proxies / CDNs (502 Bad Gateway): In silent_drop mode, Routewarden terminates the TCP socket immediately without sending an HTTP status line. If Caddy is deployed behind Cloudflare, AWS ALB, NGINX, Traefik, or any reverse proxy / CDN, the edge proxy detects an abrupt connection termination and presents a 502 Bad Gateway error to the client.
When debugging unexpected 502 errors or when clean client responses are required, switch to mode json or mode html with status_code 403 or 404.
7. JSON Configuration (Caddy REST API)
For zero-downtime environments configured via Caddy's dynamic API:
{ "handler": "routewarden", "config_file": "/etc/routewarden/routewarden.json", "enabled": true, "enable_default_patterns": true, "allowed_ips": ["10.0.0.0/8", "192.168.1.50"], "methods": ["GET", "POST"], "block_patterns": ["(?i)^/admin(/.*)?$"], "allow_patterns": ["(?i)^/admin/health$"], "response": { "mode": "json", "status_code": 403, "body": "{\"error\":\"Forbidden: Authorized Access Only\"}" }}