Great question! Managing bot traffic is a common challenge, especially since many bots ignore robots.txt and spoof user agents. Here’s a practical approach using Nginx and some additional strategies:
1. Nginx Rate Limiting
You can use Nginx’s limit_req and limit_conn modules to throttle requests per IP, which helps slow down aggressive bots.
Example:
http {
# Define a rate limit zone (10 requests per second per IP)
limit_req_zone $binary_remote_addr zone=botlimit:10m rate=10r/s;
# Limit concurrent connections per IP
limit_conn_zone $binary_remote_addr zone=connlimit:10m;
server {
# Apply the rate limit to all requests
limit_req zone=botlimit burst=20 nodelay;
limit_conn connlimit 10;
# ... your other config ...
}
}
- Adjust the numbers (
10r/s, burst=20, connlimit 10) to suit your site’s needs.
- This will slow down all clients, but most humans won’t hit these limits.
2. Block Known Bad Bots/User Agents
You can block or slow down requests with suspicious or empty user agents.
map $http_user_agent $bad_bot {
default 0;
"" 1; # Empty UA
"~*bot" 1; # Contains 'bot'
"~*crawler" 1;
"~*spider" 1;
# Add more patterns as needed
}
server {
if ($bad_bot) {
return 403;
}
}
- Note: Some legitimate bots (like Googlebot) will match these patterns, so be careful and whitelist as needed.
3. Deny Requests with No User Agent
Many bad bots don’t send a user agent at all.
if ($http_user_agent = "") {
return 403;
}
4. Other Nginx Modules
- fail2ban: Use with Nginx logs to ban IPs with suspicious behavior.
- ModSecurity: For more advanced filtering.
5. Other Approaches (Outside Nginx)
- WAF/CDN: Use a Web Application Firewall (e.g., Cloudflare, Sucuri) to filter and rate-limit bots before they reach your server.
- JavaScript Challenges: Some bots can’t handle JS, so requiring a simple JS challenge for suspicious traffic can help.
- CAPTCHA: For forms or sensitive endpoints.
- Log Analysis: Regularly analyze logs to identify and block new bad actors.
6. Whitelist Good Bots
If you want Google, Bing, etc., to crawl freely, whitelist their IP ranges or user agents.
7. Summary
- Nginx: Use
limit_req, limit_conn, block empty/suspicious user agents.
- Outside Nginx: Use WAF/CDN, log analysis, and possibly CAPTCHAs or JS challenges.
- Monitor: Regularly review logs and adjust rules as needed.
Example Combined Nginx Snippet:
http {
limit_req_zone $binary_remote_addr zone=botlimit:10m rate=10r/s;
limit_conn_zone $binary_remote_addr zone=connlimit:10m;
map $http_user_agent $bad_bot {
default 0;
"" 1;
"~*bot" 1;
"~*crawler" 1;
"~*spider" 1;
}
server {
limit_req zone=botlimit burst=20 nodelay;
limit_conn connlimit 10;
if ($bad_bot) {
return 403;
}
# ... rest of your config ...
}
}
Tip: Always test your config to avoid blocking legitimate users or search engines. Adjust thresholds as you monitor traffic.
Let me know if you want more specific examples or have a particular use case!