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/nginxcollection 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_addrthe 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.
rootorsudo, 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 versionafter install. Thecscli allowlistssubcommand 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-bouncerpackage pulls inlibnginx-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.
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
-
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 crowdsecExpected: the service starts on its own.
systemctl status crowdsecshowsActive: active (running), andsudo cscli lapi statusprintsYou can successfully interact with Local API (LAPI). The local API listens on127.0.0.1:8080and is not reachable from outside the host. -
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.yamlalready.grep -rl nginx /etc/crowdsec/acquis.yaml /etc/crowdsec/acquis.d/ 2>/dev/nullIf 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 crowdsecExpected:
reloadreturns silently. Thetype: nginxlabel is not cosmetic — it routes lines to the Nginx parser, and getting it wrong means every line is discarded as unparsed. -
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 crowdsecExpected: the install prints
downloading crowdsecurity/nginxfollowed by its dependencies, thenEnabled collections: crowdsecurity/nginx. Confirm withsudo cscli collections list(statusenabled) andsudo cscli scenarios list, which now includescrowdsecurity/http-probing,crowdsecurity/http-crawl-non_staticsand the brute-force scenarios. -
Prove that lines are parsed before you enforce anything. This is the step most people skip and then spend an afternoon on.
sudo cscli metricsExpected: an Acquisition Metrics table listing
file:/var/log/nginx/access.logwith non-zeroLines readandLines parsed. IfLines readclimbs whileLines parsedstays at zero, a customlog_formatis the usual cause. Diagnose a single line directly:sudo cscli explain --file /var/log/nginx/access.log --type nginxExpected: a tree showing each parser stage the line passed through, ending in the scenarios it was poured into. A line that dies at
s01-parsenever reaches a scenario. -
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.10Expected:
checkreports 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 crowdsecExpected:
sudo cscli parsers listshowslocal/office-whitelistas enabled. The stockcrowdsecurity/whitelistsparser already exempts RFC 1918 and loopback, which is why testing from your own LAN never raises an alert. -
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_addris that proxy, every log line carries the same handful of addresses, and every decision CrowdSec writes bans your own edge.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 nginxExpected:
nginx -tprintssyntax is okandtest is successful, and the next line inaccess.logstarts with a client address instead of your edge. List every range your provider publishes inset_real_ip_from— a missing range means those requests keep logging the proxy. Never pointreal_ip_headerat a header that arbitrary clients can set on a directly reachable server, or you have handed attackers the ability to forge who gets banned. -
Register a bouncer and install it. The Debian package registers itself during post-install when
cscliis local; the manual path below is what remote bouncers need.sudo cscli bouncers add nginx-edge-01Expected: the API key is printed once, and only once. Then install the component:
sudo apt install crowdsec-nginx-bouncerExpected: the package writes
/etc/crowdsec/bouncers/crowdsec-nginx-bouncer.confand 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.confExpected:
ENABLED=true,API_URL=http://127.0.0.1:8080, a non-emptyAPI_KEY,MODE=streamandUPDATE_FREQUENCY=10. Replace<paste-the-key-here>with the value from the previous command. -
Reload Nginx and confirm the bouncer is talking to the API.
sudo nginx -t && sudo systemctl reload nginx sudo cscli bouncers listExpected: the table lists
nginx-edge-01with aValidstatus and aLast API pulltimestamp from the last few seconds. An emptyLast API pullmeans 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 readclimbs,Lines parsedstays at zero. Yourlog_formatis not the stock combined format, or the acquisitiontypelabel is wrong. Confirm withcscli explain --fileon a real line: if it stops at the parse stage, revert that server block to the defaultlog_formator write a custom parser. Also check readability —sudo -u crowdsec test -r /var/log/nginx/access.logon distributions that run the service unprivileged.- Alerts fire but nothing is ever blocked. Check
cscli bouncers listfirst. A missingLast API pullmeans the bouncer never authenticated: the key incrowdsec-nginx-bouncer.confdoes not match one in the list, orAPI_URLpoints somewhere else.journalctl -u nginx --since -10msurfaces Lua errors from the bouncer. - Nothing triggers when you test from the office. Two overlapping causes: the stock
crowdsecurity/whitelistsparser 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 theorigincolumn.crowdsecmeans one of your scenarios fired — inspect the alert and ask whether that scenario suits your traffic.CAPIor 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 -treportingunknown directive "access_by_lua_block"means the Lua module is not loaded. Installlibnginx-mod-http-luaand reload, or remove/etc/nginx/conf.d/crowdsec_nginx.confand switch tocrowdsec-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-bouncerandcscli 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.