Set up NGINX rate limiting and security headers safely

Intermediate 25 min May 24, 2026 1,945 views
Ubuntu 24.04 Debian 12 AlmaLinux 9 Rocky Linux 9

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

#nginx #rate-limiting #ddos-protection #security-headers #fail2ban

Don't want to manage this yourself?

We handle infrastructure for businesses that depend on uptime. Fully managed, with one fixed contact who knows your setup.

You get one fixed contact who knows your setup

At their desk in Rotterdam 11:42 · reachable in a message, no ticket form

Learn more: infrastructure security hardening