basforge

Search titles, text and the “If it doesn’t work” cases.

    RU
    ManualHomelabnginx

    Bot protection and WAF in nginx: User-Agent, CrowdSec, and when to add ModSecurity or Coraza

    Layer bot and web-attack defenses: block unwanted crawlers and scanners in nginx via map, add behavioral bans in CrowdSec, and weigh when a full WAF (ModSecurity v3 or Coraza) with OWASP CRS pays off versus when it gets in the way.

    Three layers of bot and attack protection

    Catching each class of threat at the right layer keeps nginx from wasting CPU parsing every request body:

    Layer Tool What it catches Cost
    1. nginx filters User-Agent map, decoy path blocks, limit_req Self-identifying AI/SEO crawlers, basic .env/wp-login.php scanners, floods Near-zero CPU and RAM, built in
    2. Behavioral bans CrowdSec (acquis + bouncer) Scanners with spoofed User-Agent, password brute force, 404/403 storms, known botnet IPs Small CrowdSec container, almost no false positives
    3. WAF (L7 DPI) ModSecurity v3 / Coraza + OWASP CRS SQL injection, XSS, path traversal, RCE inside query params and POST bodies Higher CPU/RAM, dynamic module builds, ongoing rule tuning

    Layer 1: blocking bots and scanners in nginx

    Use two chained map blocks in the http context: the first flags unwanted crawlers (with \b word boundaries so a short token never collides with a normal browser or search engine), and the second keeps /robots.txt accessible.

    /etc/nginx/conf.d/07-bots.conf
    map $http_user_agent $bad_bot {
        default 0;
        ~*\b(?:GPTBot|Bytespider|CCBot|ClaudeBot|SemrushBot|AhrefsBot|MJ12bot)\b 1;
        "" 1; # empty User-Agent is almost always a script or scanner
    }
    Key part

    Word boundaries \b prevent accidental substring matches inside other names. Keep the list in a dedicated file; if the site sits behind Cloudflare, mirror the same names in AI Crawl Control.

    map $uri $bots_welcome {
        /robots.txt 1;
        default     0;
    }
    
    map $bad_bot$bots_welcome $deny_bot {
        10      1;
        default 0;
    }

    A second map for /robots.txt and a combined $deny_bot flag: when a listed bot (1) requests anything other than /robots.txt (0), $bad_bot$bots_welcome evaluates to 10 and nginx returns 403. Requests to /robots.txt (11) go through.

    server {
        listen 443 ssl;
        server_name example.org;
    
        if ($deny_bot) {
            return 403;
        }
    
        # For non-PHP sites: drop WordPress and phpMyAdmin scanners immediately
        location ~* \.(?:php|asp|aspx|jsp)$ {
            return 444;
        }
    }

    Inside server: reject listed bots and common scanner probes (.php on a non-PHP site, wp-admin, .env) before they touch the backend.

    If internal healthchecks or monitoring scripts send an empty User-Agent, remove "" 1; from $bad_bot or pass an explicit User-Agent in those scripts.

    Layer 2: CrowdSec instead of manual IP blocklists

    Manual deny lists in nginx cannot keep up with distributed scanners rotating IPs every ten minutes. CrowdSec tails /var/log/nginx/access.log and error.log through the crowdsecurity/nginx collection, spots attack patterns (dictionary 404 sweeps, LFI/SQLi URL probes, brute force), and pushes bans to an nftables bouncer on a direct host or an nginx/Cloudflare bouncer behind a CDN (CrowdSec with Traefik behind Cloudflare).

    In 90% of personal VPS, API, and homelab setups, nginx-hardening + limit_req + bot map + CrowdSec covers the threat model without a full WAF.

    Layer 3: WAF (ModSecurity v3 and Coraza) — tradeoffs

    A WAF (Web Application Firewall) inspects headers, URLs, and every POST/JSON request body against OWASP Core Rule Set (CRS) signatures — catching SQL injection, XSS, command injection, and path traversal before the request reaches app code.

    Two main open-source engines for nginx:

    • ModSecurity v3 (libmodsecurity + ModSecurity-nginx) — the established option with the widest package and guide coverage; maintained by OWASP after Trustwave transferred the project in 2024.
    • Coraza + coraza-nginx (or via Caddy / CrowdSec AppSec) — a Go rewrite compatible with SecLang and OWASP CRS; takes less maintenance if CrowdSec is already running on the server (WAF with CrowdSec AppSec).

    What you get

    • Virtual patching. Blocks a known vulnerability in an older CMS or third-party web app while you wait for an upstream fix.
    • Request-body inspection. Catches attacks hidden inside form payloads, JSON, and cookies where access_log and limit_req cannot look.
    • Ready OWASP CRS rulesets cover standard attack classes right after setup.

    What it costs

    • False positives. Rich-text editors, comments containing SQL/HTML snippets, or complex API JSON regularly trigger 403 until you add per-rule-ID exclusions.
    • Build maintenance. The base nginx.org package ships no WAF connector — you have to recompile the dynamic module on every minor nginx update (or offload WAF duties to CrowdSec AppSec).
    • CPU and memory overhead. Running deep regex checks against every request noticeably cuts throughput on a small VPS.
    If… Use
    you run a static site, a small custom API, or homelab services nginx (limit_req + map) + CrowdSec on logs — skip the WAF
    you host a heavy plugin-based CMS (WordPress, legacy portal) or must inspect POST forms CrowdSec AppSec (if CrowdSec is already installed) or ModSecurity v3 / Coraza with OWASP CRS
    you are enabling a WAF on a live site for the first time run SecRuleEngine DetectionOnly for 1–2 weeks first, tune out false positives, then switch to On

    How to check

    1. Validate syntax and reload:
      sudo nginx -t && sudo systemctl reload nginx
    2. Verify that a listed bot receives 403 on pages and 200 on /robots.txt:
      curl -s -o /dev/null -w "page:%{http_code}\n" -A "Mozilla/5.0 (compatible; GPTBot/1.0)" https://example.org/
      # page:403
      curl -s -o /dev/null -w "robots:%{http_code}\n" -A "Mozilla/5.0 (compatible; GPTBot/1.0)" https://example.org/robots.txt
      # robots:200
    3. Verify that a normal User-Agent and unlisted bot names pass through:
      curl -s -o /dev/null -w "browser:%{http_code}\n" -A "Mozilla/5.0" https://example.org/
      # browser:200

    If it doesn’t work

    A bot rule ~*nbot accidentally blocked LinkedInBot and OpenBot

    Cause
    The substring nbot matched inside longer bot names because no word boundaries were set.
    Fix
    Match whole words with \b word boundaries or explicit delimiters: ~*\b(?:GPTBot|Bytespider|SemrushBot|AhrefsBot)\b.

    A bot blocked by User-Agent cannot even fetch /robots.txt

    Cause
    if ($bad_bot) { return 403; } ran before every location, including /robots.txt where crawl restrictions live.
    Fix
    Combine two map blocks ($bad_bot and $bots_welcome) so /robots.txt still returns 200 while all other paths return 403.

    After turning on a WAF (ModSecurity/Coraza + OWASP CRS), regular users get 403 when posting comments or Markdown with code snippets

    Cause
    OWASP CRS rules see SQL keywords (SELECT ... FROM) or <script> inside form text and flag them as attacks.
    Fix
    Always run a WAF in SecRuleEngine DetectionOnly mode for 1–2 weeks first, collect false positives from the audit log, and exclude the noisy rule IDs per URI.

    Bots still bypass the User-Agent block by pretending to be Chrome

    Cause
    User-Agent is a plain client-supplied string: an nginx filter stops only crawlers that identify themselves (AI crawlers, SEO bots).
    Fix
    For aggressive scraping and brute force with forged User-Agent headers, combine limit_req (Limits & access) with behavioral log bans in CrowdSec.