The access log of my small self-hosted API is full of random scans and login attempts. nginx can limit requests per client IP with a few lines. It does not replace real security, but it stops simple abuse and keeps a small backend from overload.
In the http block, for example /etc/nginx/conf.d/ratelimit.conf:
limit_req_zone $binary_remote_addr zone=api:10m rate=5r/s;
limit_req_zone $binary_remote_addr zone=login:10m rate=10r/m;
limit_req_status 429;
In the server block:
location /api/ {
limit_req zone=api burst=20 nodelay;
proxy_pass http://127.0.0.1:8080;
}
location = /login {
limit_req zone=login burst=5;
proxy_pass http://127.0.0.1:8080;
}
sudo nginx -t && sudo systemctl reload nginx
rate=5r/s is the steady rate. nginx tracks it in milliseconds, so it means one request every 200 ms, not 5 at once. burst=20 lets a client go over the rate for a short time, with the extra requests waiting in a queue. nodelay sends those burst requests at once instead of slowing them down. Without it, a page that makes many API calls at once feels slow. The 10m is shared memory for the zone. 1 MB holds about 16,000 IP addresses, so 10 MB is plenty.
Two mistakes
The first is no burst at all. A browser can send 3 requests in the same millisecond, and without burst two of them get errors. I did this on my first try and the web UI broke in strange ways.
The second is the wrong client IP behind a proxy. If nginx sits behind a load balancer or a CDN, $binary_remote_addr is the proxy’s address, and all users share one limit. Set up the real IP module first:
set_real_ip_from 10.0.0.0/8; # your proxy range
real_ip_header X-Forwarded-For;
real_ip_recursive on;
Only trust the header from proxies you control. Otherwise clients can fake their IP.
Check
for i in $(seq 1 40); do curl -s -o /dev/null -w "%{http_code}\n" https://example.com/api/ping; done | sort | uniq -c
Some 200, then 429. Limited requests also show up in the error log as limiting requests.