Skip to content

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:

caddy.logtext
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 option

To 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 ​

Caddyfile Schemacaddy
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 ​

DirectiveTypeDefaultDescription
config_filestring""Path to a routewarden.json file loaded as the base config. Inline Caddyfile fields take precedence over the file.
enabledbooltrueEnables or disables Routewarden inspection.
debugboolfalseEnables verbose diagnostic logging in Caddy's logger.
security_logbooltrueEmits single-line structured JSON security events on stdout for CrowdSec, SIEMs, or log aggregators on blocked requests.
enable_default_patternsbooltrueBlocks high-risk files (.env, .git, .aws, .ssh, .sql, .bak, etc.).
enable_default_allow_patternsbooltrueWhitelists standard files like /robots.txt, /favicon.ico, /sitemap.xml.
check_queryboolfalseWhen enabled, also evaluates query parameters for sensitive file targets.
block_patternslist[]Additional regex patterns to intercept.
allow_patternslist[]Regex patterns that should always be allowed through.
allowed_ipslist[]IPv4, IPv6, or CIDR blocks exempted from checks.
allowed_asnslist[]Autonomous System Numbers (AS64500, 64500) allowed to bypass inspection. Bare allowed_asns clears inherited list.
blocked_asnslist[]Autonomous System Numbers whose client IPs are blocked. Requires asn_db.
asn_dbstring""Path to local JSON ASN routing snapshot database.
bot_defense_levelstring""Preset bot defense level (off, light, standard, strict, aggressive). Activates pre-tuned bot defenses.
block_ai_botsboolfalseEnables automatic blocking of known AI crawlers and LLM training bots.
ai_bot_profilestring""AI bot profile: train_only (default), all, aggressive, or custom.
block_user_agentslist[]Custom regex patterns matching client User-Agents to block.
allow_user_agentslist[]Custom regex patterns matching client User-Agents to allow.
detect_browser_impersonationboolfalseCross-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_clientsboolfalseBlocks automated HTTP client libraries (requests, Guzzle, reqwest, axios, curl) and headless framework headers (X-Playwright, X-Puppeteer, X-Cypress, Sec-WebDriver).
verify_search_engine_botsboolfalseVerifies Googlebot, Bingbot, and Applebot authenticity via FCrDNS.
honeypot_trap_pathslist[]Hidden trap paths that trigger instant sliding-window IP bans.
trap_ban_durationstring"24h"Ban duration for trapped IPs (e.g., 24h, 1h, 30m).
trusted_proxieslist[]Trusted upstream reverse proxies / CIDRs for real client IP extraction.
methodslist["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:

caddyfile
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.py from MaxMind GeoLite2/GeoIP2 ASN CSVs.
  • Clearing Inherited Lists: In multi-site setups where a base block configures allowed_asns, specifying a bare allowed_asns with no arguments in a child block explicitly clears any inherited ASN allowlist.
  • Anti-Spoofing: Header values like CF-Connecting-ASN are never trusted; only the TCP socket address or sanitized IP from trusted_proxies is 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 ​

PrioritySource
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_patterns just to change mode.
  • 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 CategoryCompiled RegexIntercepted 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 ResourceCompiled RegexPurpose
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 ​

ModeOptionsTypical Use Case
jsonstatus_code, bodyREST API protection with clean JSON error
htmlstatus_code, bodyCustom branded 404 or 403 error page
textstatus_code, bodyMinimal plain-text rejection
redirectstatus_code, redirect_urlDeflect scanners to honeypot or warning page
captchacaptcha.provider, captcha.site_keyChallenge suspicious visits via Cloudflare Turnstile/hCaptcha
silent_dropNoneReset TCP connection immediately (conn.Close())
gzip_bombstatus_code, gzip_bomb_mbActive defense memory-exhaustion trap
tarpittarpit_delay_msSlowloris defense trickling bytes to tie up scanner concurrency
ratelimitstatus_code, retry_after_seconds429 Too Many Requests response
proxyproxy_urlTransparent canary/forensics honeypot mirror
fake_successstatus_code, bodySynthetic decoy responses (wp-login, fake .env)
ai_poisonNoneServes HTTP 200 with prompt injection directives & noai robots tag
markov_tarpittarpit_delay_msProcedural word stream trickle to exhaust crawler context windows
pow_challengepow_difficulty, pow_secret, pow_timeout_secondsCryptographic 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:

caddy-api.jsonjson
{  "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\"}"  }}

Released under the MIT License.