A practical NGINX guide to request limits, login throttling, security headers, reverse-proxy IPs, verification, and monitoring without blocking legitimate visitors.
Prerequisites
- Root or sudo access
- NGINX installed
- Basic understanding of HTTP and web security
What this solves
NGINX can limit requests per client and send useful browser security headers. This reduces the impact of simple request floods and repeated login attempts, while giving browsers clearer rules for handling your pages. It does not replace upstream DDoS protection, and a rate limit that is too strict can block real customers. Start with measurements, test the limits, and keep a rollback path.
Before you change anything
Use a staging server if possible. Save the current configuration and confirm how NGINX is packaged on your system. The standard NGINX build includes the request and connection limit modules; there is no separate nginx-module-http-limit-req package to install. If you use a custom build, inspect nginx -V and the build options first. The examples below assume an existing HTTPS virtual host.
nginx -V 2>&1
sudo nginx -T > nginx-config-before-limits.txt
sudo nginx -t
The configuration dump can contain internal hostnames and paths. Store it securely and do not publish it. On Debian or Ubuntu, install the normal nginx package if NGINX is not already present. On RHEL-family systems, use the NGINX package from the repository you operate and document its version.
Define a small, measurable request limit
Place the zone in the http context, outside a server block. The key $binary_remote_addr uses the client IP address as NGINX sees it. The zone name is shared with the locations below. Choose the rate from your own access logs, not from an assumed universal threshold.
http {
limit_req_zone $binary_remote_addr zone=per_client:10m rate=10r/s;
server {
listen 443 ssl;
server_name example.com;
location / {
limit_req zone=per_client burst=20 nodelay;
limit_req_status 429;
proxy_pass http://your_app;
}
}
}
Merge these directives into your existing configuration rather than adding a second http or server block. A burst allows short traffic spikes. With nodelay, requests within the burst are handled immediately; excess requests are rejected. The 429 response is explicit for clients and monitoring. Do not use a low global limit for payment, webhook, or API traffic without checking normal peak use.
Protect login routes separately
Login endpoints can use a second zone with a lower rate. This is a traffic control, not a substitute for account-level throttling and multifactor authentication. If many users share one public IP address, a per-IP limit affects them together. Account-level controls belong in the application.
# In the existing http context:
limit_req_zone $binary_remote_addr zone=login_per_ip:10m rate=5r/m;
# In the existing server context:
location = /login {
limit_req zone=login_per_ip burst=5 nodelay;
limit_req_status 429;
proxy_pass http://your_app;
}
Change /login to your actual route. An exact-match location may override an existing location with authentication, caching, or proxy headers, so carry those settings across. For a PHP application, adapt the existing FastCGI location instead of copying a proxy_pass example.
Add security headers with an application check
Headers are useful only when they match the application. Add them at the HTTPS server level and test login, payments, downloads, and embedded content. nosniff and a conservative referrer policy are usually simple starting points. A Content Security Policy needs an inventory of actual script and asset sources; do not paste a generic policy into production.
# In the existing HTTPS server context:
add_header X-Content-Type-Options "nosniff" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
add_header X-Frame-Options "SAMEORIGIN" always;
NGINX header inheritance can change when a location has its own add_header directives. Inspect the effective configuration with nginx -T and test more than one route. If your site intentionally uses cross-origin embedding, review X-Frame-Options before applying it.
Handle reverse proxies carefully
If NGINX is behind a trusted reverse proxy, a limit based on $binary_remote_addr may otherwise group all visitors under the proxy IP. Configure the real-IP module only after you know the proxy's exact IP ranges and the header it sends. Never trust all private networks or an arbitrary X-Forwarded-For header from the public internet. Confirm support with nginx -V; this module is not included in every custom build. After configuration, compare logged client IPs with the proxy logs.
Verify your setup
Test syntax before reloading. Then make a small number of controlled requests against a nonproduction route, check that a normal visitor succeeds, and check that exceeding the chosen rate returns 429. Do not run a load test against production without authorization. Monitor rejected requests and customer reports for at least a normal traffic cycle.
sudo nginx -t
sudo systemctl reload nginx
curl -I https://example.com/
sudo journalctl -u nginx --since '15 minutes ago'
Check the NGINX access and error log paths configured on your host. A successful syntax test proves only that the configuration can be parsed; it does not prove the rate is appropriate for your traffic. Record the before-and-after error rate and keep the saved configuration for a quick rollback.
Common issues
Everyone appears to have the same IP: verify the exact trusted proxy ranges and real-IP header. Customers receive 429 during normal use: review the route's peak requests and increase the rate or burst after measuring. Headers disappear on one route: inspect add_header inheritance in nested locations. The service fails to reload: read the nginx -t error and restore the previous configuration before retrying.
Geographic blocking is not a reliable substitute for these controls and can exclude legitimate customers. It also requires a maintained database and the matching GeoIP module. This guide deliberately leaves it out of the baseline. For large traffic floods, arrange protection upstream of your server and involve your hosting provider.
Running this in production?
Set an owner for the configuration, monitor 429 responses, and review thresholds when traffic or application routes change. Keep your NGINX and operating-system packages patched. For a broader check of patch level, SSH access, firewall, logging, and backups, see Binadit Server Scan. The scan can help identify configuration risks, but no single configuration or scan guarantees protection from every attack.
Reference: NGINX request limiting documentation, NGINX headers documentation, and NGINX real-IP documentation.
Automated install script
Run this to automate the entire setup
#!/usr/bin/env bash
set -euo pipefail
# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'
# Default values
DOMAIN=""
BACKUP_DIR="/tmp/nginx_backup_$(date +%s)"
usage() {
echo "Usage: $0 -d domain.com"
echo " -d: Domain name for nginx configuration"
echo " -h: Show this help"
exit 1
}
log_info() { echo -e "${GREEN}[INFO]${NC} $1"; }
log_warn() { echo -e "${YELLOW}[WARN]${NC} $1"; }
log_error() { echo -e "${RED}[ERROR]${NC} $1"; }
cleanup() {
log_error "Script failed. Restoring from backup..."
if [ -d "$BACKUP_DIR" ]; then
cp -r "$BACKUP_DIR"/* /etc/nginx/ 2>/dev/null || true
systemctl reload nginx 2>/dev/null || true
fi
exit 1
}
trap cleanup ERR
while getopts "d:h" opt; do
case $opt in
d) DOMAIN="$OPTARG" ;;
h) usage ;;
*) usage ;;
esac
done
if [ -z "$DOMAIN" ]; then
log_error "Domain name is required"
usage
fi
if [ "$EUID" -ne 0 ]; then
log_error "This script must be run as root"
exit 1
fi
# Auto-detect distribution
if [ -f /etc/os-release ]; then
. /etc/os-release
case "$ID" in
ubuntu|debian)
PKG_MGR="apt"
PKG_UPDATE="apt update"
PKG_INSTALL="apt install -y"
NGINX_CONF_DIR="/etc/nginx"
SITES_DIR="sites-available"
SITES_ENABLED="sites-enabled"
;;
almalinux|rocky|centos|rhel|ol|fedora)
PKG_MGR="dnf"
PKG_UPDATE="dnf update -y"
PKG_INSTALL="dnf install -y"
NGINX_CONF_DIR="/etc/nginx"
SITES_DIR="conf.d"
SITES_ENABLED="conf.d"
;;
amzn)
PKG_MGR="yum"
PKG_UPDATE="yum update -y"
PKG_INSTALL="yum install -y"
NGINX_CONF_DIR="/etc/nginx"
SITES_DIR="conf.d"
SITES_ENABLED="conf.d"
;;
*)
log_error "Unsupported distribution: $ID"
exit 1
;;
esac
else
log_error "Cannot detect distribution"
exit 1
fi
log_info "[1/8] Backing up existing nginx configuration..."
mkdir -p "$BACKUP_DIR"
if [ -d "$NGINX_CONF_DIR" ]; then
cp -r "$NGINX_CONF_DIR"/* "$BACKUP_DIR/"
fi
log_info "[2/8] Updating package repositories..."
$PKG_UPDATE
log_info "[3/8] Installing NGINX..."
$PKG_INSTALL nginx
systemctl enable nginx
log_info "[4/8] Creating rate limiting configuration..."
cat > "$NGINX_CONF_DIR/conf.d/rate-limiting.conf" << 'EOF'
# Rate limiting zones
limit_req_zone $binary_remote_addr zone=basic:10m rate=10r/s;
limit_req_zone $binary_remote_addr zone=login:10m rate=2r/m;
limit_req_zone $binary_remote_addr zone=api:10m rate=100r/m;
limit_conn_zone $binary_remote_addr zone=conn_limit_per_ip:10m;
limit_conn_zone $server_name zone=perserver:10m;
# Request limits
client_max_body_size 10M;
client_body_timeout 12;
client_header_timeout 12;
send_timeout 10;
client_body_buffer_size 16K;
client_header_buffer_size 1k;
large_client_header_buffers 2 1k;
# Status codes for rate limiting
limit_req_status 429;
limit_conn_status 429;
EOF
log_info "[5/8] Creating security headers configuration..."
cat > "$NGINX_CONF_DIR/conf.d/security-headers.conf" << 'EOF'
# Security headers
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header X-Content-Type-Options "nosniff" always;
add_header Referrer-Policy "no-referrer-when-downgrade" always;
add_header Content-Security-Policy "default-src 'self' http: https: data: blob: 'unsafe-inline'" always;
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
# Hide NGINX version
server_tokens off;
EOF
log_info "[6/8] Creating DDoS protection configuration..."
cat > "$NGINX_CONF_DIR/conf.d/ddos-protection.conf" << 'EOF'
# Bot detection and limiting
map $http_user_agent $limit_bots {
~*(google|bing|yandex|msnbot) "";
~*(AhrefsBot|MJ12bot|DotBot) $binary_remote_addr;
~*(SemrushBot|BLEXBot|DomainStatsBot) $binary_remote_addr;
default "";
}
limit_req_zone $limit_bots zone=bots:10m rate=1r/m;
# Slow HTTP attack protection
client_body_timeout 5s;
client_header_timeout 5s;
EOF
log_info "[7/8] Creating virtual host configuration..."
if [ "$SITES_DIR" = "sites-available" ]; then
VHOST_FILE="$NGINX_CONF_DIR/$SITES_DIR/$DOMAIN"
ENABLED_FILE="$NGINX_CONF_DIR/$SITES_ENABLED/$DOMAIN"
else
VHOST_FILE="$NGINX_CONF_DIR/$SITES_DIR/$DOMAIN.conf"
fi
cat > "$VHOST_FILE" << EOF
server {
listen 80;
listen [::]:80;
server_name $DOMAIN www.$DOMAIN;
# Include security configurations
include $NGINX_CONF_DIR/conf.d/security-headers.conf;
# Apply connection and rate limits
limit_conn conn_limit_per_ip 20;
limit_conn perserver 200;
limit_req zone=basic burst=20 nodelay;
limit_req zone=bots burst=1;
# Document root
root /var/www/html;
index index.html index.htm index.nginx-debian.html;
# Main location
location / {
try_files \$uri \$uri/ =404;
}
# API endpoints with stricter limits
location /api/ {
limit_req zone=api burst=50 nodelay;
try_files \$uri \$uri/ =404;
}
# Login/admin pages with very strict limits
location ~ ^/(login|admin|wp-admin) {
limit_req zone=login burst=2 nodelay;
try_files \$uri \$uri/ =404;
}
# Block common attack vectors
location ~ /\. {
deny all;
access_log off;
log_not_found off;
}
location ~ ~$ {
deny all;
access_log off;
log_not_found off;
}
# Error and access logs
error_log /var/log/nginx/$DOMAIN.error.log;
access_log /var/log/nginx/$DOMAIN.access.log;
}
EOF
# Enable site for Debian-based systems
if [ "$SITES_DIR" = "sites-available" ]; then
ln -sf "$VHOST_FILE" "$ENABLED_FILE"
fi
# Set proper permissions
chmod 644 "$NGINX_CONF_DIR/conf.d"/*.conf
chmod 644 "$VHOST_FILE"
chown root:root "$NGINX_CONF_DIR/conf.d"/*.conf "$VHOST_FILE"
log_info "[8/8] Testing and restarting NGINX..."
nginx -t
systemctl restart nginx
# Create basic index page if it doesn't exist
if [ ! -f /var/www/html/index.html ]; then
cat > /var/www/html/index.html << EOF
<!DOCTYPE html>
<html>
<head><title>$DOMAIN - DDoS Protected</title></head>
<body>
<h1>Welcome to $DOMAIN</h1>
<p>This server is protected against DDoS attacks with NGINX rate limiting.</p>
</body>
</html>
EOF
chmod 644 /var/www/html/index.html
fi
# Verification checks
log_info "Verifying configuration..."
if nginx -t &>/dev/null; then
log_info "✓ NGINX configuration is valid"
else
log_error "✗ NGINX configuration test failed"
exit 1
fi
if systemctl is-active nginx &>/dev/null; then
log_info "✓ NGINX is running"
else
log_error "✗ NGINX is not running"
exit 1
fi
if curl -s -o /dev/null -w "%{http_code}" "http://localhost" | grep -q "200"; then
log_info "✓ Web server is responding"
else
log_warn "⚠ Web server may not be responding correctly"
fi
log_info "Configuration completed successfully!"
log_info "Rate limiting zones configured:"
log_info " - Basic: 10 req/sec per IP"
log_info " - Login/Admin: 2 req/min per IP"
log_info " - API: 100 req/min per IP"
log_info " - Connections: 20 per IP, 200 per server"
log_info "Security headers and DDoS protection enabled"
log_info "Test your configuration: curl -I http://$DOMAIN"
Review the script before running. Execute with: bash install.sh