Skip to content

NGINX Configuration Reference ​

Configuration schema, options, and parameters for NGINX Warden (github.com/routewarden/nginx-warden).


1. Lua Module Initialization ​

Initialize Routewarden using routewarden.new(config) within NGINX's init_by_lua_block or init_worker_by_lua_block. The returned instance is re-entrant and shared across request worker threads:

http {    lua_package_path "/usr/local/openresty/site/lualib/?.lua;/etc/nginx/lua/lib/?.lua;/etc/nginx/lua/lib/?/init.lua;;";    init_by_lua_block {        local routewarden = require("resty.routewarden")        warden = routewarden.new({            -- Configuration options go here        })    }}

2. Complete Configuration Options ​

routewarden-config.lualua
warden = routewarden.new({    -- Load base configuration from shared JSON policy file (optional)    config_file = "/etc/routewarden/routewarden.json",    -- Master toggle    enabled = true,                        -- Default: true    debug = false,                         -- Default: false (outputs trace logs via ngx.log)    security_log = true,                   -- Default: true (emits JSON security events for CrowdSec/SIEM)    -- Built-in rules    enable_default_patterns = true,        -- Default: true (blocks .env, .git, .aws, dumps, actuator)    enable_default_allow_patterns = true,  -- Default: true (permits /robots.txt, /sitemap*.xml, /.well-known/*)    -- Deep inspection    check_query = false,                   -- Default: false (evaluates unescaped query string)    check_headers = {                      -- Default: {} (inspects forwarded headers for path smuggling)        "X-Forwarded-Uri",        "X-Rewrite-URL"    },    -- HTTP Method filtering    methods = { "GET", "HEAD" },           -- Default: { "GET" } (non-matching methods bypass checks)    -- IP / CIDR Subnet Allowlist    allowed_ips = {        "127.0.0.1",        "10.0.0.0/8",        "192.168.1.0/24",        "::1"    },    -- ASN Allowlist & Offline Routing DB    allowed_asns = { "AS13335", "64500" },    blocked_asns = { "AS138699" },    asn_db = "/etc/routewarden/asn.json",    trusted_proxies = { "10.0.0.0/8" },    -- AI Bot & Crawler Defense    bot_defense_level = "standard",    block_ai_bots = true,    ai_bot_profile = "train_only",    block_user_agents = { "(?i)badbot" },    allow_user_agents = { "(?i)goodbot" },    detect_browser_impersonation = true,    block_script_clients = true,    verify_search_engine_bots = true,    honeypot_trap_paths = { "/hidden-trap" },    trap_ban_duration = "24h",    -- Custom regular expressions (PCRE-compatible)    block_patterns = {        "(?i)^/admin(/.*)?$",        "(?i)^/api/internal(/.*)?$"    },    -- Safe pattern exemptions (takes precedence over block patterns)    allow_patterns = {        "(?i)^/api/internal/health$"    },    -- Response action configuration    response = {        mode = "json",                     -- Options: json, html, text, xml, redirect, captcha,                                           -- silentDrop, gzipBomb, tarpit, fakeSuccess,                                           -- rateLimitChallenge, proxy, infiniteStream,                                           -- aiPoison, markovTarpit, powChallenge        status_code = 403,        body = '{"error":"Access Denied"}',        headers = {            ["X-Frame-Options"] = "DENY"        },        redirect_url = "https://example.com/blocked",        proxy_url = "http://127.0.0.1:9999/canary",        gzip_bomb_mb = 10,        retry_after_seconds = 300,        tarpit_delay_ms = 1000,        tarpit_max_duration_seconds = 60,        stream_size_mb = 100,        pow_difficulty = 16,        pow_secret = "your-cryptographic-pow-secret",        pow_timeout_seconds = 300,        captcha = {            provider = "turnstile",        -- Options: turnstile, hcaptcha, recaptcha            site_key = "0x4AAAAAAAxxyyzz",            title = "Security Verification"        }    }})

3. Options Reference Table ​

KeyTypeDefaultDescription
config_filestringnilPath to a routewarden.json base configuration file. Inline Lua table options override file settings.
enabledbooleantrueEnables or disables Routewarden inspection.
debugbooleanfalseWhen true, logs normalization transformations and rule matching details.
security_logbooleanfalseEmits single-line structured JSON security events on stdout for CrowdSec and SIEM auto-ban.
enable_default_patternsbooleantrueIntercepts common exposure targets (.env, .git, .aws, database dumps, actuator, debug files).
enable_default_allow_patternsbooleantruePermits standard discovery files (/robots.txt, /sitemap*.xml, /.well-known/*, /security.txt).
check_querybooleanfalseInspects raw and URL-decoded query string parameters for sensitive targets.
methodstable{"GET"}Array of HTTP verbs to inspect. Verbs outside this list bypass inspection.
allowed_ipstable{}Array of IPv4/IPv6 addresses or CIDR subnets allowed to bypass path inspection.
allowed_asnstable{}Array of Autonomous System Numbers ("AS64500", "64500") allowed to bypass inspection.
blocked_asnstable{}Array of Autonomous System Numbers whose client IPs are blocked. Requires asn_db.
asn_dbstringnilPath to local JSON ASN routing snapshot file.
bot_defense_levelstringnilPreset bot defense level ("off", "light", "standard", "strict", "aggressive"). Activates pre-tuned bot defenses.
block_ai_botsbooleanfalseEnables automatic blocking of known AI scrapers & LLM training crawlers.
ai_bot_profilestringnilAI bot profile: train_only (default), all, aggressive, or custom.
block_user_agentstable{}Array of custom PCRE regular expressions matching client User-Agents to block.
allow_user_agentstable{}Array of custom PCRE regular expressions matching client User-Agents to allow.
detect_browser_impersonationbooleanfalseCross-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_clientsbooleanfalseBlocks automated HTTP client libraries (requests, Guzzle, reqwest, axios, curl) and headless automation framework headers (X-Playwright, X-Puppeteer, X-Cypress, Sec-WebDriver).
verify_search_engine_botsbooleanfalseCryptographically verifies search engine bot authenticity via FCrDNS.
honeypot_trap_pathstable{}Array of decoy paths that trigger instant sliding-window IP bans.
trap_ban_durationstring"24h"Ban duration for trapped client IPs (e.g. 24h, 1h, 30m).
trusted_proxiestable{}Array of trusted upstream proxy CIDRs for real client IP extraction.
block_patternstable{}Array of custom PCRE regular expressions to block.
allow_patternstable{}Array of custom PCRE regular expressions to exempt from blocking.
responsetable{ mode = "json", status_code = 403 }Response execution table.

4. Config File (config_file) ​

Instead of writing all rules inline inside NGINX configuration blocks, point Routewarden at a shared routewarden.json file. Inline Lua table fields override file values, so you can maintain a single shared security policy and customize behavior per virtual host:

http {    init_by_lua_block {        local routewarden = require("resty.routewarden")        -- Load base policy from shared file with inline overrides        warden = routewarden.new({            config_file = "/etc/routewarden/routewarden.json",            # Override response mode just for this NGINX instance:            mode = "tarpit"        })    }}

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 Lua options in routewarden.new({ ... })
2 (base)Fields from config_file (routewarden.json)
  • Non-nil inline values override corresponding file values.
  • Empty/omitted inline directives defer to the file — you don't need to duplicate block_patterns just to change the response mode.
  • A missing or malformed file causes an immediate startup error, preventing silent fallback to insecure defaults.

TIP

Mount routewarden.json into your OpenResty container as a volume or Kubernetes ConfigMap to share uniform security rules across multiple NGINX instances.


5. ASN Allowlisting (allowed_asns & asn_db) ​

NGINX Warden supports Autonomous System Number (ASN) based allowlisting using an offline JSON routing snapshot compiled via scripts/build-asn-db.py:

lua
http {
    init_by_lua_block {
        local routewarden = require("resty.routewarden")

        warden = routewarden.new({
            allowed_asns = { "AS13335", "64500" },
            asn_db = "/etc/routewarden/asn.json",
            trusted_proxies = { "10.0.0.0/8" },
            response = {
                mode = "json",
                status_code = 403
            }
        })
    }
}
  • In-Memory Performance: Parsed into a longest-prefix radix table during worker initialization with zero runtime network/DNS overhead.
  • Strict Peer Resolution: Client-supplied ASN headers are never trusted; only the TCP socket address or sanitized IP from trusted_proxies is evaluated.
  • For complete snapshot instructions and architecture details, see the ASN Filtering Guide.

6. Response Modes Table ​

Routewarden for NGINX supports 13 response modes matching the core engine:

ModeKey SettingsAction
jsonstatus_code, bodySends structured JSON with application/json header.
htmlstatus_code, bodyServes custom HTML error page.
textstatus_code, bodyReturns plain text with text/plain.
xmlstatus_code, bodyServes XML payload with application/xml.
redirectstatus_code, redirect_urlRedirects client via HTTP 301, 302, or 307.
captchacaptcha.provider, captcha.site_keyServes interactive Cloudflare Turnstile, hCaptcha, or reCAPTCHA page.
silentDropNoneTerminates TCP connection immediately via NGINX HTTP 444.
gzipBombgzip_bomb_mbDelivers highly compressed zero-byte gzip stream that expands in client RAM (supports fractional sizes e.g. 0.5).
tarpittarpit_delay_ms, tarpit_max_duration_secondsTrickles bytes slowly to tie up bot sockets and worker pools.
fakeSuccessstatus_code (200), body (optional)Deceptive honeypot returning realistic .env, .git/HEAD, or Spring Actuator mock data.
rateLimitChallengeretry_after_seconds (300)Returns HTTP 429 with standard Retry-After header.
proxyproxy_urlTransparently proxies request to an internal canary or forensic honeypot container.
infiniteStreamstream_size_mb (100)Streams high-speed random characters to exhaust scanner storage and buffers.
powChallengepow_difficulty, pow_secret, pow_timeout_secondsCryptographic Proof-of-Work challenge solver (<2KB inline HTML/JS) returning HTTP 429.

7. Client IP Resolution ​

Routewarden evaluates client addresses using the following priority:

  1. X-Forwarded-For header (first non-internal IP)
  2. X-Real-IP header
  3. Socket address ngx.var.remote_addr

When deploying behind Cloudflare, AWS ALB, or an outer proxy, set standard NGINX real-ip directives:

real_ip.confnginx
set_real_ip_from 10.0.0.0/8;set_real_ip_from 172.16.0.0/12;set_real_ip_from 192.168.0.0/16;real_ip_header X-Forwarded-For;real_ip_recursive on;

Released under the MIT License.