How to block bots with nginx and Apache

Intermediate3 min readUpdated

GET /learn/implementation/block-bots-with-nginx-and-apache/ Accept text/html text/markdown

Short answer

In nginx, match unwanted user agents with a map and return 403, cap request rates with limit_req, and block networks with deny or the geo module. In Apache, use mod_rewrite conditions on HTTP_USER_AGENT and Require not ip inside RequireAll. These rules stop bots that announce themselves or come from a few networks. Bots that copy a browser's user agent and rotate IP addresses need other signals.

Server rules are free and fast, and they run before your application spends any work on a request. They only see what the request declares about itself. A bot that sends a current Chrome user agent from a fresh residential IP address passes every rule on this page. Use these rules to remove the bots that announce themselves or hammer you from a few networks, so your logs and any detection you add later can focus on the rest.

How do you block bots by user agent in nginx?

Use a map to turn the User-Agent header into a flag, then return 403 when the flag is set. The map block goes in the http context, for example in a file under /etc/nginx/conf.d/:

nginx
map $http_user_agent $block_ua {
    default                                                  0;
    ""                                                       1;
    ~*(python-requests|scrapy|go-http-client|curl/|wget/)    1;
}

server {
    server_name example.com;

    if ($block_ua) {
        return 403;
    }
}

~* makes the match case-insensitive. Test with nginx -t before you reload. A rule like this only stops bots that tell the truth about what they are; anything sending a browser's user agent walks past it. Check the list against your own traffic first: uptime monitors, payment webhooks and partner integrations often use curl or a Go client. If they do, apply the rule only to form posts or to the paths bots attack.

Never allow a search engine by user agent alone, because anyone can claim to be Googlebot. Check with a reverse DNS lookup, as shown in how to verify Googlebot and other good bots. For AI crawlers that do identify themselves, our guide on how to block AI crawlers covers the user agents to match.

How do you rate limit bots in nginx?

limit_req_zone defines a counter and limit_req applies it. Both zone definitions and limit_req_status go in the http context:

nginx
limit_req_zone $binary_remote_addr zone=per_ip:10m rate=10r/s;
limit_req_zone $binary_remote_addr zone=login:10m rate=10r/m;
limit_req_status 429;

server {
    server_name example.com;

    location / {
        limit_req zone=per_ip burst=40 nodelay;
        proxy_pass http://127.0.0.1:8080;
    }

    location = /login {
        limit_req zone=login burst=5 nodelay;
        proxy_pass http://127.0.0.1:8080;
    }
}

The numbers are starting points. If nginx also serves your images and scripts, a page view can fire dozens of requests, so raise the general limit or leave static locations out of it. The rate limiting guide covers what to key on besides IP.

How do you block IP ranges in nginx?

For a few ranges, use deny from the access module. Rules are checked in order and the first match wins:

nginx
location / {
    deny 192.0.2.0/24;
    deny 2001:db8::/32;
    allow all;
    proxy_pass http://127.0.0.1:8080;
}

For longer lists, the geo module scales better and keeps the ranges in their own file:

nginx
geo $blocked_net {
    default 0;
    include /etc/nginx/blocked-networks.conf;
}

server {
    if ($blocked_net) {
        return 403;
    }
}

Each line in blocked-networks.conf is a range and a value, such as 198.51.100.0/24 1;. The geo block goes in the http context.

If nginx sits behind a CDN or load balancer, it sees the proxy's address. Configure the realip module with set_real_ip_from and real_ip_header first, so deny and geo act on the visitor's address. IP lists also go stale fast. Bots on residential proxies use home addresses that real customers will hold tomorrow, so prefer short bans on observed behaviour over permanent lists.

How do you block bots in Apache .htaccess?

With mod_rewrite, match the user agent and return 403 with the F flag:

apache
RewriteEngine On
RewriteCond %{HTTP_USER_AGENT} ^$ [OR]
RewriteCond %{HTTP_USER_AGENT} (python-requests|scrapy|go-http-client|curl/|wget/) [NC]
RewriteRule ^ - [F]

[NC] makes the match case-insensitive and [OR] joins the two conditions. In .htaccess this needs AllowOverride FileInfo on the directory.

To block IP ranges in Apache 2.4, use Require not ip from mod_authz_core. A negative Require cannot stand alone, so wrap it in RequireAll with a positive rule:

apache
<RequireAll>
    Require all granted
    Require not ip 192.0.2.0/24 198.51.100.0/24
    Require not ip 2001:db8::/32
</RequireAll>

In .htaccess this needs AllowOverride AuthConfig. Do not mix it with the Apache 2.2 Order, Allow and Deny directives, which behave differently when combined.

mod_ratelimit is often mistaken for a request limiter. It limits response bandwidth per client. For request counts, use a third-party module such as mod_evasive or mod_qos, put nginx or a CDN in front, or let fail2ban ban addresses from the logs.

How do fail2ban and CrowdSec help?

Both read your logs and ban addresses that misbehave. fail2ban adds a firewall rule for a set time. It ships filters for common cases, including nginx-limit-req, which reads the "limiting requests" errors nginx writes when limit_req rejects a client, and apache-badbots. A jail in /etc/fail2ban/jail.local:

txt
[nginx-limit-req]
enabled  = true
port     = http,https
logpath  = /var/log/nginx/error.log
findtime = 600
maxretry = 10
bantime  = 3600

CrowdSec works the same way with more detection scenarios, and it shares a community blocklist built from attacks seen on other servers. Its remediation components enforce bans in nginx, in the host firewall or at Cloudflare.

Keep bans short. One address can be a mobile carrier's NAT gateway with thousands of customers behind it.

Tools that help

StopBots is published by Kairal, which is one of the tools listed. The list is not a ranking.

  • fail2ban is free and open source, and it is enough to turn nginx and Apache rejections into firewall bans on a single server.
  • CrowdSec is open source, adds behaviour scenarios and a shared blocklist, and runs across many servers.
  • Cloudflare on its free plan filters known bot patterns before they reach your server; see our Cloudflare guide.
  • Kairal integrates at a reverse proxy or the CDN and adds device and behavioural signals that server rules cannot see, with protection set per endpoint.

Common questions

Can nginx detect bots?

nginx can match what a request declares: the user agent, the IP address, the path and the request rate. Without extra modules it does not run JavaScript in the browser or read TLS fingerprints, so it cannot tell a real browser from a well disguised bot.

Should I block bots by user agent?

Block user agents you never want, such as scraping libraries and empty values on form posts, because it costs nothing. Do not count it as protection against a determined attacker, since any script can send a current Chrome user agent string.

Does mod_ratelimit limit requests in Apache?

No. mod_ratelimit limits the bandwidth of each response sent to a client. To limit request counts in Apache, use a third-party module such as mod_evasive or mod_qos, a rate-limiting proxy in front, or fail2ban reading the access log.