Skip to content

Install CrowdSec on Nginx and enforce bans with a bouncer

Learn how to install CrowdSec on an Nginx server and connect the nginx bouncer so detected attacks are actually blocked. You will also allowlist your own addresses and log the real visitor IP when a CDN sits in front.

This guide shows Linux admins how to install CrowdSec, an open-source intrusion detection tool, on an Nginx server and make it block attackers. Many people are surprised to find that CrowdSec on its own blocks nothing. It reads your logs, spots abuse and records a ban decision, yet the requests keep arriving. The fix is a bouncer, a small separate component that fetches those decisions from CrowdSec’s local API (application programming interface) and enforces them in Nginx. By the end, you will have detection and blocking working, your own addresses allowlisted so you cannot lock yourself out, and Nginx logging the real visitor IP (Internet Protocol) address even behind a CDN (content delivery network).

What you’ll accomplish

  • Get CrowdSec parsing the Nginx access and error logs, with proof that lines are being read and understood.
  • Install the crowdsecurity/nginx collection so the scenarios that matter for a web server are active.
  • Allowlist your office egress and monitoring probes before any enforcement exists.
  • Register and install a bouncer, and watch a real ban take effect and then expire.
  • Make $remote_addr the actual client address behind a CDN or load balancer, so decisions name attackers instead of your edge.

Prerequisites

  • A Debian 12 / Ubuntu 22.04 or newer host, or a RHEL 9 family host, already serving traffic with Nginx and writing an access log.
  • root or sudo, and outbound HTTPS so the machine can reach the hub and, if you keep it enabled, the central API.
  • CrowdSec 1.6.x. Check with cscli version after install. The cscli allowlists subcommand used below arrived in 1.6.8; on anything older, use the parser whitelist shown alongside it.
  • For the Nginx bouncer specifically: an Nginx build with the Lua module available. On Debian and Ubuntu the crowdsec-nginx-bouncer package pulls in libnginx-mod-http-lua. Without Lua, use the firewall bouncer instead — same API key, same decisions, enforcement moves to nftables or iptables.
  • One honest packaging note: the Debian post-install script runs a detection wizard that may already have written an acquisition file for you. Fedora and RHEL packaging does not. Check before writing your own, or you will tail the same file twice.

How it works

Four things run, and it helps to name them separately. The log processor (the crowdsec service) tails the files in your acquisition config, runs each line through parsers that turn text into structured events, and pours those events into scenarios — leaky buckets that fill on matching events and overflow when a threshold is crossed inside a window. An overflow produces an alert and, normally, an attached decision: ban this IP for four hours. The local API stores both in SQLite. The bouncer authenticates to that API with its own key, pulls the decision list, and enforces it.

Flow diagram showing Nginx access and error logs feeding CrowdSec acquisition, then parsers and scenarios, with an overflow writing a decision into the local API on 127.0.0.1 port 8080, a dashed exchange with the CrowdSec central API for the community blocklist, and the nginx bouncer polling the local API to either return a 403 ban page or pass the request upstream

The bouncer runs in stream mode by default: it fetches the full decision list once, then polls for deltas every few seconds and answers every request from an in-process cache. That is why a ban you add by hand takes a few seconds to bite, and why the bouncer keeps working if the local API restarts. Live mode — one API call per request — exists and is almost never what you want.

The community blocklist is the piece with no fail2ban equivalent. If you register with the central API, your instance sends signals — source IP, scenario name, timestamp — about the attacks it sees, and in exchange pulls a curated list of addresses many other instances have reported. Those arrive as ordinary decisions with origin CAPI, and your bouncer enforces them like your own, so a scanner is blocked before it has probed you once. The costs are equally real: you send attack telemetry to a third party, you trust someone else’s list, and a shared NAT or CGNAT address that misbehaved elsewhere can arrive pre-banned. Our fail2ban configuration guide covers the simpler alternative in depth.

Step-by-step

  1. Install the repository and the package. The install script adds the CrowdSec package repository for your distribution and nothing else.

    curl -s https://install.crowdsec.net | sudo sh
    sudo apt install crowdsec

    Expected: the service starts on its own. systemctl status crowdsec shows Active: active (running), and sudo cscli lapi status prints You can successfully interact with Local API (LAPI). The local API listens on 127.0.0.1:8080 and is not reachable from outside the host.

  2. Point acquisition at the Nginx logs. Configuration lives in /etc/crowdsec/acquis.d/, one file per source. Check for an existing entry first — on Debian the post-install wizard may have written /etc/crowdsec/acquis.yaml already.

    grep -rl nginx /etc/crowdsec/acquis.yaml /etc/crowdsec/acquis.d/ 2>/dev/null

    If nothing comes back, write your own:

    sudo tee /etc/crowdsec/acquis.d/nginx.yaml >/dev/null <<'EOF'
    filenames:
      - /var/log/nginx/access.log
      - /var/log/nginx/error.log
    labels:
      type: nginx
    EOF
    sudo systemctl reload crowdsec

    Expected: reload returns silently. The type: nginx label is not cosmetic — it routes lines to the Nginx parser, and getting it wrong means every line is discarded as unparsed.

  3. Install the Nginx collection from the hub. A collection bundles the parsers and scenarios for one piece of software.

    sudo cscli hub update
    sudo cscli collections install crowdsecurity/nginx
    sudo systemctl reload crowdsec

    Expected: the install prints downloading crowdsecurity/nginx followed by its dependencies, then Enabled collections: crowdsecurity/nginx. Confirm with sudo cscli collections list (status enabled) and sudo cscli scenarios list, which now includes crowdsecurity/http-probing, crowdsecurity/http-crawl-non_statics and the brute-force scenarios.

  4. Prove that lines are parsed before you enforce anything. This is the step most people skip and then spend an afternoon on.

    sudo cscli metrics

    Expected: an Acquisition Metrics table listing file:/var/log/nginx/access.log with non-zero Lines read and Lines parsed. If Lines read climbs while Lines parsed stays at zero, a custom log_format is the usual cause. Diagnose a single line directly:

    sudo cscli explain --file /var/log/nginx/access.log --type nginx

    Expected: a tree showing each parser stage the line passed through, ending in the scenarios it was poured into. A line that dies at s01-parse never reaches a scenario.

  5. Allowlist yourself before enforcement exists. Do this now, not after you have locked yourself out. On 1.6.8 and later:

    sudo cscli allowlists create office --description "office egress and monitoring probes"
    sudo cscli allowlists add office 203.0.113.10 198.51.100.0/28
    sudo cscli allowlists check 203.0.113.10

    Expected: check reports the address as allowlisted and names the list. Allowlists are evaluated against decisions from every origin, including the community blocklist, which is what makes them the right tool. On older releases, use a whitelist parser instead — it suppresses only alerts your own instance would raise, not decisions arriving from elsewhere:

    sudo tee /etc/crowdsec/parsers/s02-enrich/office-whitelist.yaml >/dev/null <<'EOF'
    name: local/office-whitelist
    description: "do not alert on office egress or monitoring probes"
    whitelist:
      reason: "office NAT and uptime checks"
      ip:
        - "203.0.113.10"
      cidr:
        - "198.51.100.0/28"
    EOF
    sudo systemctl reload crowdsec

    Expected: sudo cscli parsers list shows local/office-whitelist as enabled. The stock crowdsecurity/whitelists parser already exempts RFC 1918 and loopback, which is why testing from your own LAN never raises an alert.

  6. Fix the real client address if anything sits in front of Nginx. When a CDN, cloud load balancer or reverse proxy terminates the connection, $remote_addr is that proxy, every log line carries the same handful of addresses, and every decision CrowdSec writes bans your own edge.

    Side-by-side comparison showing that without set_real_ip_from the Nginx log records the CDN edge address and CrowdSec bans the edge, blocking all traffic, while with set_real_ip_from and real_ip_header the log records the true client address and only the abusive client is banned

    Fix it in Nginx, not in CrowdSec, so both detection and enforcement see the same address:

    sudo tee /etc/nginx/conf.d/realip.conf >/dev/null <<'EOF'
    set_real_ip_from 198.51.100.0/24;
    real_ip_header X-Forwarded-For;
    real_ip_recursive on;
    EOF
    sudo nginx -t && sudo systemctl reload nginx

    Expected: nginx -t prints syntax is ok and test is successful, and the next line in access.log starts with a client address instead of your edge. List every range your provider publishes in set_real_ip_from — a missing range means those requests keep logging the proxy. Never point real_ip_header at a header that arbitrary clients can set on a directly reachable server, or you have handed attackers the ability to forge who gets banned.

  7. Register a bouncer and install it. The Debian package registers itself during post-install when cscli is local; the manual path below is what remote bouncers need.

    sudo cscli bouncers add nginx-edge-01

    Expected: the API key is printed once, and only once. Then install the component:

    sudo apt install crowdsec-nginx-bouncer

    Expected: the package writes /etc/crowdsec/bouncers/crowdsec-nginx-bouncer.conf and an include at /etc/nginx/conf.d/crowdsec_nginx.conf. Set the key and the endpoint:

    sudo sed -i 's|^API_KEY=.*|API_KEY=<paste-the-key-here>|' /etc/crowdsec/bouncers/crowdsec-nginx-bouncer.conf
    sudo grep -E '^(ENABLED|API_URL|API_KEY|MODE|UPDATE_FREQUENCY)=' /etc/crowdsec/bouncers/crowdsec-nginx-bouncer.conf

    Expected: ENABLED=true, API_URL=http://127.0.0.1:8080, a non-empty API_KEY, MODE=stream and UPDATE_FREQUENCY=10. Replace <paste-the-key-here> with the value from the previous command.

  8. Reload Nginx and confirm the bouncer is talking to the API.

    sudo nginx -t && sudo systemctl reload nginx
    sudo cscli bouncers list

    Expected: the table lists nginx-edge-01 with a Valid status and a Last API pull timestamp from the last few seconds. An empty Last API pull means the bouncer never authenticated — wrong key, wrong URL, or Nginx did not load the include.

Validate it works

Setup is not evidence. Ban a throwaway address by hand, with a short duration so you cannot forget about it:

sudo cscli decisions add --ip 203.0.113.42 --duration 4m --type ban
sudo cscli decisions list

Expected: a row with source 203.0.113.42, action ban, an expiry counting down from four minutes, and origin cscli. Use an address you actually control so you can test from it. Wait one poll interval, then request the site from that address:

curl -sS -o /dev/null -w '%{http_code}\n' https://example.com/

Expected: 403 and the bouncer’s ban page from the banned source, 200 from anywhere else. Then clean up and confirm the release propagates:

sudo cscli decisions delete --ip 203.0.113.42
sudo cscli decisions list --ip 203.0.113.42

Expected: 1 decision(s) deleted, then No active decisions. Traffic from that address is served normally again within one poll interval.

To prove detection rather than enforcement, drive real 404s at the site from an address outside your allowlist and outside RFC 1918 — crowdsecurity/http-probing overflows after enough of them in a short window.

sudo cscli alerts list
sudo cscli alerts inspect <alert-id>

Expected: an alert naming the scenario and the source, and an inspect view showing the events that filled the bucket. If alerts appear but nothing is enforced, the problem is on the bouncer side; if neither appears, the problem is parsing.

Troubleshooting

  • Lines read climbs, Lines parsed stays at zero. Your log_format is not the stock combined format, or the acquisition type label is wrong. Confirm with cscli explain --file on a real line: if it stops at the parse stage, revert that server block to the default log_format or write a custom parser. Also check readability — sudo -u crowdsec test -r /var/log/nginx/access.log on distributions that run the service unprivileged.
  • Alerts fire but nothing is ever blocked. Check cscli bouncers list first. A missing Last API pull means the bouncer never authenticated: the key in crowdsec-nginx-bouncer.conf does not match one in the list, or API_URL points somewhere else. journalctl -u nginx --since -10m surfaces Lua errors from the bouncer.
  • Nothing triggers when you test from the office. Two overlapping causes: the stock crowdsecurity/whitelists parser exempts private ranges, and you allowlisted your own egress in step 5. Both are correct. Test from a cloud instance or a mobile connection before assuming detection is broken.
  • A legitimate visitor or your own address is banned and you did not do it. Run cscli decisions list --ip <address> and read the origin column. crowdsec means one of your scenarios fired — inspect the alert and ask whether that scenario suits your traffic. CAPI or a list name means the community blocklist, common for CGNAT and shared mobile ranges; deleting the decision works until the next pull, so add the address to an allowlist instead.
  • Nginx refuses to start after installing the bouncer. nginx -t reporting unknown directive "access_by_lua_block" means the Lua module is not loaded. Install libnginx-mod-http-lua and reload, or remove /etc/nginx/conf.d/crowdsec_nginx.conf and switch to crowdsec-firewall-bouncer-nftables.
  • You locked yourself out over SSH. That is the firewall bouncer, not the Nginx one. Get to a provider console, then systemctl stop crowdsec-firewall-bouncer and cscli decisions delete --all. Add the allowlist entry before starting it again.

When this is the wrong approach

If all you need is “ban the address that failed SSH five times”, fail2ban is the smaller, more predictable tool: one daemon, regex filters you can read in a minute, a direct call to your firewall, no API keys, no hub versioning, no external service. CrowdSec asks you to maintain more moving parts — a Go daemon holding a SQLite database, at least one bouncer with its own credential, hub content that needs cscli hub upgrade and a reload — and to decide whether sharing attack telemetry fits your compliance obligations. If it does not, you can run with the central API disabled, but you have then paid the complexity and declined the feature that justified it.

It is also the wrong layer when your origin sits behind a CDN that terminates TLS: blocking at the origin still means the request crossed the internet and consumed a connection, so the decision belongs at the CDN, which is what the provider-specific bouncers are for. And CrowdSec is a poor answer to plain volumetric load from many addresses — that is a rate-limiting problem, and Nginx already has the tool, covered in our limit_req guide. On a host with a handful of known clients, an allow-only firewall policy beats any behavioural detector; detection earns its keep when the client set is open-ended.

The authoritative references are the CrowdSec documentation and the crowdsec repository, which carries the hub content and the release notes that tell you which cscli subcommands exist in your version.

If this is the kind of work you’d rather never own again, it’s the daily job of Managed Cloud Ops — book an infrastructure review.