Halloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PCHalloween DealsAmazon USOctober picks are moving - compare before checkoutAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk11 min

How to Block DDoS Attacks Using NGINX: A Practical Configuration Guide

A practical NGINX DDoS guide covering leaky-bucket request limits, per-IP connection ceilings, trusted proxy headers, dry-run rollout, stream protection, troubleshooting, and the limits of origin-side mitigation.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

NGINX can absorb and reject many application-layer DDoS attempts by limiting requests, concurrent connections, and bandwidth at the origin. The dependable pattern is to key those limits to the real client address, apply stricter rules to expensive endpoints, observe them in dry-run mode, and then enforce values measured from normal traffic. NGINX is not a substitute for upstream DDoS scrubbing: if an attack fills the network link before packets reach your server, an origin configuration cannot process that traffic.

This guide shows how to build the controls, avoid false positives caused by proxies and NAT, roll them out safely, and decide when protection must move upstream.

As an Amazon Associate I earn from qualifying purchases.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

What NGINX can and cannot block

NGINX is an origin-side mitigation layer. It sees traffic after it has reached your host, load balancer, or reverse-proxy tier, so it can make a useful decision before forwarding a request to an application server. Its open-source controls are especially effective against HTTP request floods, connection hoarding, and abusive access to costly endpoints such as login, search, checkout, or report generation.

Those controls do not make an exposed server invisible. A volumetric attack that saturates the ISP circuit, cloud instance interface, or provider edge leaves no capacity for NGINX to receive and evaluate requests. Use a CDN or managed DDoS-scrubbing service in front of the origin for that class of attack, and restrict the origin firewall so attackers cannot bypass the front door.

#1 Best Overall
FortiGate-40F Firewall Appliance - 5 Gigabit Ethernet RJ45 Ports, Ideal for Small Businesses (Appliance Only, No Subscription) (FG-40F)
  • Compact and Efficient Design: The FortiGate 40F is designed for small to mid-sized businesses and enterprise branch offices, featuring a compact, fanless desktop form factor that ensures quiet operation and minimizes space usage.
  • Robust Connectivity Options: Equipped with 5 GE RJ45 ports, including 1 WAN port and 4 internal ports, this model provides essential connectivity and flexibility for various network configurations in a small-scale environment.
  • High-Performance Security: Offers up to 1 Gbps IPS throughput and 600 Mbps threat protection throughput, using Fortinet’s purpose-built security processor technology to deliver industry-leading performance and protection for SSL encrypted traffic.
  • Advanced Threat Protection: Integrated with Fortinet’s AI-powered FortiGuard Labs, the FortiGate 40F offers comprehensive cybersecurity, identifying and mitigating both known and unknown threats to maintain robust security across your network.
  • Simplified Management and Deployment: Features a user-friendly management console that provides comprehensive network automation and visibility, coupled with Zero Touch Integration with Fortinet’s Security Fabric for easy deployment.

Choose the control that matches the attack

Control What it limits Typical scope What happens when the limit is reached Important qualification
limit_req_zone and limit_req HTTP request-processing rate Usually one endpoint or a group of endpoints, keyed by client identity Requests can be delayed or rejected; a deliberate status such as 429 is recommended Uses a leaky-bucket algorithm. A rate is not a promise of application capacity.
limit_conn_zone and limit_conn Simultaneous connections or requests in progress Per client key, location, or virtual server New work is rejected after the concurrent ceiling is reached HTTP/2 and HTTP/3 concurrent requests are counted separately, so test modern clients.
limit_rate Bytes delivered per connection Usually a response or location Each connection is slowed It does not stop a client opening many connections; pair it with connection limits.
Stream-module connection limits Concurrent TCP sessions Non-HTTP services proxied by the stream module Excess source-key connections are rejected Use a key representing the real source, and account for shared NAT.
CDN or managed scrubbing Traffic before it reaches the origin link Provider edge and upstream network Provider-specific filtering, challenge, or absorption Required when the access link or provider edge is the bottleneck.

Prepare the traffic path before writing limits

Map every hop

Write down whether clients connect directly to NGINX, through a load balancer, through a CDN, or through several reverse proxies. The address NGINX sees is the address used by the limit key. If that address belongs to a proxy, thousands of legitimate visitors can be placed in one bucket. If NGINX accepts an attacker-controlled forwarding header, an attacker can simply change the apparent address on every request.

Restore the real client address safely

For a proxied deployment, configure the real-IP module only for the published address ranges of proxies you control or explicitly trust. A documentation-only example is:

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
http {
    set_real_ip_from 192.0.2.0/24;
    real_ip_header X-Forwarded-For;
    real_ip_recursive on;
}

The 192.0.2.0/24 network is reserved for examples; it is not a provider range to copy into production. Replace it with the current ranges supplied by your own load balancer or CDN, and do not enable trust for arbitrary Internet addresses. If there are multiple hops, verify which hop appends and which hop overwrites the header, then test the resulting $remote_addr in access logs.

Measure normal behavior

Collect several representative periods rather than choosing a number from a blog post. Record requests per second and concurrency separately for anonymous pages, authenticated users, APIs, uploads, login, search, and other expensive operations. Break out known shared networks such as offices, mobile carriers, schools, and corporate forward proxies. A single global per-IP rate that fits a residential user may lock out an entire office, while a generous global rate can leave a login endpoint exposed.

Build HTTP request and connection limits

Define shared-memory zones at http scope

Zones hold the counters that locations consult. The key is normally $binary_remote_addr, a compact representation of the address. Size and rate values below are illustrative starting points, not performance guarantees:

http {
    limit_req_zone  $binary_remote_addr zone=per_ip_req:10m rate=5r/s;
    limit_conn_zone $binary_remote_addr zone=per_ip_conn:10m;

    server {
        location = /login {
            limit_req zone=per_ip_req burst=10 nodelay;
            limit_conn per_ip_conn 10;
            limit_req_dry_run on;
            limit_req_status 429;
        }

        location / {
            limit_conn per_ip_conn 50;
        }
    }
}

limit_req_zone and limit_conn_zone must be declared in the http context. The enforcement directives can be placed in a server or location. A 10 MB zone is simply the storage allocation for keys and counters; it does not mean ten megabytes per visitor.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #2
Firewall Appliance 10GbE Mini PC with SFP+, Intel Alder Lake N100 (4C/4T) 4xIntel I226-V 2.5GbE 2*Intel 82599ES 10GbE Firewall LTE Router Support AES-NI (N150, NO RAM NO ROM) (N150, NO RAM NO ROM)
  • 【Professional Firewall & NAS SERVER】OAKNODE 10gbe Firewall Appliance Mini PC-MGNASN, a powerful professional firewall router pc equipped with a 12th Gen Alder Lake N100 4C/4T up to 3.4GHz TDP only 6W with Intel UHD Graphics which maximizes the performance of the 2.5GbE port & SFP+ port, bring you a smooth secured and encrypted network environment.
  • 【Rich I/O to meet your needs】Firewall Appliance MGNASN With HDMI 2.0+DP 1.4+TYPE-C(dp 1.2) Support for 3x4K@60Hz together, Dual DDR4 RAM slot support for up to 1x32GB SO-Dimm laptop DDR5 Ram Maximum 5600Mhz and 1xM.2 NVMe/PCIe 3.0x1 2280 SSD slot +1*SATA 3.0 SSD/HDD slots (install externally), also it support boot from TF card slot and it also support PXE/AWOL/Watchdog/GPIO etc. which is perfect for your firewall appliance、VM、Router、home Server needs.
  • 【2xSFP+ 10GbE + 4x2.5GbE】This Firewall Router equipped with 2xIntel 82599ES 10gbe network card and 4*Intel i226-V network card speed maximum up to 2.5GbE(need other device like router, cables etc. also support 2.5Gbe/10gbe)which can bring you more faster and professional network usage(some system not release drivers yet) suggest to install version of below systems: pf-sense plus 23.0X or CE 2.7.X, OPNsense 22.1, OpenWrt, ROS7, ESXI 8 , Proxmox, CentOS etc).
  • 【4G LTE Function supported】This model also support 4G LTE function(mini PCIE slot for 4G modem) and SIM card slot which you can use it as a IOT devices for your server.
  • 【Quality With Warranty】If you have any questions or requirements(like OS installation/ drives/bios updates etc.) on OAKNODE Firewall mini pc MGNASN, PLEASE feel free to contact us. We offered 12 Months warranty for it and WE'LL REPLY YOUR Questions within 12 hours(during Workdays).

Apply request limits where work is expensive

The example protects /login more tightly than ordinary pages. Repeat the pattern for password reset, account creation, search, checkout, API mutation, report generation, and any route that consumes disproportionate CPU, database time, or upstream connections. Use separate zones or keys when two classes of traffic need different policies. A static asset path generally needs a connection ceiling but not the same request rate as an authentication route.

Use a connection ceiling as a second line

Request-rate limits and concurrent-connection limits solve different problems. A client can send requests slowly while holding many sockets open, or open several sockets to evade a per-connection bandwidth limit. Apply limit_conn to the relevant location or server and choose a ceiling from observed keep-alive, HTTP/2, and HTTP/3 behavior. Because multiplexed protocols can carry several concurrent requests over one connection, validate the count with real clients before enforcing a low value.

Understand request-limit behavior

The leaky-bucket model

NGINX implements request limiting with a leaky-bucket algorithm. The configured rate represents the long-term processing pace for each key. Arrivals above that pace are either queued for delayed processing or rejected when the queue is exhausted. This smooths short spikes without allowing an unlimited backlog.

Choose a burst policy

  • No burst: the configured rate is enforced immediately. This is strict and can penalize normal page loads that request several resources together.
  • burst=N with delay: up to N excess requests wait and are released at the configured rate. This is gentler but can increase latency.
  • burst=N nodelay: requests inside the burst are passed immediately; once the burst is exhausted, new requests are rejected. This protects latency for a short legitimate burst while keeping a hard ceiling.

Start with a burst that reflects a real user action, not an arbitrary large queue. A login form may generate one request, while a single-page application can make several API calls after sign-in. Measure both patterns.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Return a deliberate status

Set limit_req_status 429; when a request is rejected so clients and observability systems can distinguish throttling from an application failure. Configure the application or edge layer to present a short retry message without revealing internal details. Do not turn a rejection into a generic success response; that hides the attack and misleads clients.

Roll out in dry-run mode

Dry-run mode records what the limit would do without delaying or rejecting the request. It is the safest way to discover shared-IP false positives and to check whether a proposed burst accommodates normal traffic.

Rank #3
Netgate 1100 pfSense+ Security Gateway - Firewall, Router, VPN
  • BUSINESS READY - pfSense+ software updates included for product lifetime. Netgate TAC Lite technical support included. One year hardware warranty included.
  • COMPLETE - Pre-loaded with pfSense+ software to get up and running fast. Simply unbox it and start customizing for your secure edge networking needs. Free help with setup from our expert Technical Assistance Center (TAC) available 24/7/365.
  • POWERFUL - A dual core ARM Cortex-A53 1.2 GHz delivers near gigabit routing of common home iPerf3 traffic and in excess of 650 Mbps of firewall throughput.
  • COMPACT - Low power draw, a compact form factor, and silent operation allow it to run unnoticed when placed on a desktop, wall, or rack.
  • FLEXIBLE - Three (3) 1 GbE switched (WAN/LAN/OPT) ports allow you to configure three separate 1 GbE switched ports for upto a gigabit of bi-directional traffic.
  1. Deploy the zones and location rules with limit_req_dry_run on;. Keep the connection limit in observation mode by collecting current connection counts before enforcing a low ceiling.
  2. Generate ordinary traffic from home, mobile, office, VPN, and automated clients. Include HTTP/1.1, HTTP/2, and HTTP/3 where your service supports them.
  3. Inspect access and error logs, upstream queueing, latency, and 4xx/5xx rates. Record which key, endpoint, and client network would have been delayed or rejected.
  4. Raise the rate or burst for legitimate shared networks, or use a more appropriate key and endpoint policy. Do not solve a proxy problem by making every user’s limit unlimited.
  5. Enforce the narrowest useful rule first, normally on an expensive endpoint. Set the rejection status to 429 and remove or turn off dry-run for that location only.
  6. Keep a measured, broader connection ceiling as a final safeguard. Watch authentication success, support reports, CPU, memory, database load, and upstream latency during a busy period.
  7. Change one value at a time and document the observed traffic range, the reason for the change, and the rollback value.

NGINX can be tested before reload with nginx -t; apply a validated configuration with a graceful reload such as nginx -s reload or your operating system’s NGINX service command.

Prevent false positives from NAT and forward proxies

IP-based controls identify an address, not a human. A carrier-grade NAT gateway, company proxy, university network, or household router can represent many people with one public address. If you count all of them together, a reasonable per-user rate can become an unreasonable per-building rate.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use the real-IP module only behind trusted proxy ranges, and test the complete chain. Common failure modes include:

  • Every visitor appears as the CDN: the proxy address was not replaced with the client address, so one bucket contains everyone.
  • Attackers rotate addresses instantly: an untrusted forwarding header is being accepted, allowing clients to choose their own key.
  • Users behind a corporate gateway are throttled: the limit is too low for a shared network or is applied globally instead of to the costly endpoint.
  • IPv4 and IPv6 behave differently: logging and keying are inconsistent across address families; verify both paths rather than assuming the IPv4 result applies.

When stronger identity is available, consider an application-level account or token key for authenticated actions, while retaining an IP-based ceiling as a broad safety net. Do not remove the IP control entirely: unauthenticated attack traffic still needs a key.

Add bandwidth controls without mistaking them for DDoS protection

limit_rate reduces the delivery speed of each response. It can protect a congested origin from a few clients downloading large objects, and it can make a single connection less costly. It does not limit how many connections a client opens. Combine it with limit_conn, cache large public objects where appropriate, and use an upstream edge for traffic that threatens the link itself.

Apply a bandwidth policy selectively. Slowing every response can make normal downloads unusable, while slowing only high-volume locations preserves interactive pages. Measure egress throughput and completion time before and after the change.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
VNOPN Fanless Firewall Appliance Intel J3710 4C/4T, Firewall Mini PC, 4 x Intel i226 LAN Ports, Network Gateway, Soft Router, Support PF-Sense/OPN-Sense, AES-NI (8GB RAM 128GB SSD)
  • 【Processor & OS】Firewall Mini PC with Intel J3710 CPU up to 2.64GHz, 4Cores 4threads 2MB L2 Cache, TDP 6.5w, supports AES-NI. It tested with pf-sens/opn-sense linux ubuntu and other popular open source os. ("DEL" key to enter BIOS)
  • 【Interfaces】The firewall pc has 4 * Intel I226 lan ports, 2 * USB3.0 ports, 1 * RS232COM port, 2 * HD port, 1 * DC port. Equipped with VESA mount, you can install the micro pc behind the monitor to save space.
  • 【Fanless Design】only 6.5W; fanless heat dissipation design, aluminum alloy shell, efficient and fast heat dissipation, which can withstand temperatures up to 60°C. support 24/7 hours working, no noise.
  • 【RAM & Storage】The firewall router equipped with 8G DDR3 RAM, max support 8GB; 128GB mSATA SSD, up to 512GB. Not support HDD. Size:5.27 * 4.98 * 1.43 inches, Weigh:500g, small but powerful.
  • 【12 Months Service】You will get a firewall pc and accessories,If you encounter any problems during the use, please contact us through Amazon, we have a professional and efficient team dedicated to serving you.

Limit TCP services with the stream module

HTTP directives do not protect a database, TLS passthrough listener, or other raw TCP service. For a service proxied by NGINX’s stream module, define a stream connection zone and cap simultaneous sessions:

stream {
    limit_conn_zone $binary_remote_addr zone=stream_per_ip:10m;

    server {
        listen 443;
        proxy_pass app_tls_backend:443;
        limit_conn stream_per_ip 20;
    }
}

The upstream name and listener in this snippet are examples of a stream topology; use the backend and port that exist in your environment. Apply the same real-IP trust discipline as HTTP, and account for clients behind NAT. A connection cap protects session count, not the bandwidth of an already established session, so pair it with upstream capacity controls where available.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Use an upstream edge for volumetric attacks

When packet volume consumes the access link, NGINX never gets a chance to reject the requests. Put a CDN or managed scrubbing service in front of the origin, point public DNS at that edge, and allow only the provider’s current egress ranges through the origin firewall where the architecture permits. Remove alternate DNS records and exposed origin addresses that let attackers connect directly.

Keep NGINX limits at the origin even with an upstream service. They still protect application workers from abusive requests that pass the edge, and they provide a second policy layer for login, APIs, and other expensive routes. Coordinate thresholds so the edge does not retry or challenge traffic in a way that creates a new burst at the origin.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Monitor the controls after enforcement

A limit is successful only when it reduces harmful work without damaging normal service. Track:

  • Requests by status, endpoint, client key, and protocol version.
  • Would-be and actual throttles, including delayed versus rejected requests.
  • Active connections, keep-alive counts, and HTTP/2 or HTTP/3 concurrent streams.
  • Origin CPU, memory, worker utilization, upstream queue depth, database connections, and response latency.
  • Network ingress and egress, packet loss, and the saturation point of the host or provider link.
  • Authentication success, checkout completion, API error rates, and legitimate-user complaints.

Alert on sudden changes in rejected requests and on a rise in latency or upstream queueing even when CPU is low. A low CPU reading does not prove that the network or connection table is healthy.

Best Value
Firewall Mini PC, Intel J1900 4-Port i210 Router, 4GB RAM 64GB SSD
  • 【CPU Optimized for Firewall Mini PCs】This firewall appliance is powered by Intel Quad-Core Celeron J1900, 64-bit, up to 2.0 GHz, supporting software-based encryption. Energy-efficient and reliable, it runs 24/7 for home or small office networks, handling VPNs, multi-WAN routing, and basic firewall tasks efficiently.
  • 【4×Intel i210 Ports】Equipped with four Intel i210 network controllers, each delivering up to 1 GbE for reliable multi-WAN routing, VPN connections, VLAN management, and stable performance in small office or home firewall deployments
  • 【Memory & Storage】This Firewall Mini PC comes with 4 GB DDR3L RAM and a 64 GB mSATA SSD, providing reliable performance for basic networking tasks. AMI BIOS with ACPI support ensures stable system operation and energy-efficient 24/7 use
  • 【Flexible System Compatibility】Compatible with Windows 10, Linux, and professional firewall systems such as pfSense, OPNsense, and VyOS, ensuring stable network management for home or small office use
  • 【After-Sales Support:】This compact, fanless, and silent firewall keeps your network secure. Includes lifetime technical support and a 30-day money-back guarantee!

Troubleshoot common symptoms

Legitimate users receive 429 responses

Check whether the key is a proxy or NAT address, whether the endpoint naturally makes several requests at once, and whether a retrying client is amplifying its own traffic. Confirm the real-IP chain, then adjust the endpoint’s rate or burst from measured data. Avoid raising a global limit when only one route is affected.

The rule appears to do nothing

Confirm the zone is declared in http, the limiting directive is inherited by the intended location, and the request reaches this NGINX instance rather than an alternate load balancer or origin address. Check that dry-run is not still enabled and that the key is changing as expected in logs.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Attackers bypass the CDN

Find direct DNS records, leaked origin addresses, health-check listeners, and firewall rules that allow the entire Internet. Restrict origin access to the edge’s current ranges and rotate exposed addresses when necessary. Origin limits cannot compensate for an openly reachable alternate path.

Connections are rejected while request rates look normal

This usually indicates socket hoarding, slow clients, keep-alive behavior, or multiplexed protocol concurrency rather than a request-rate flood. Inspect active-connection data and raise or narrow the connection rule only after confirming normal protocol behavior.

The link remains saturated despite strict limits

The traffic is arriving faster than the link can carry it, so local rejection is too late. Contact the transit, hosting, CDN, or scrubbing provider and move filtering upstream; retain NGINX rules for traffic that does reach the origin.

When an application-layer product is appropriate

F5 NGINX App Protect DoS is a separate, licensed product for organizations that need controls beyond the open-source directives. Its policy documentation describes standard, conservative, and none mitigation modes, along with signatures, bad-actor detection, automation-tool detection, and TLS fingerprinting. Evaluate licensing, deployment architecture, encrypted-traffic handling, and operational ownership separately from the configuration shown here. The open-source request and connection modules remain useful regardless of that decision.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A practical decision sequence

  1. Can traffic reach the origin? If the access link is saturated, engage upstream mitigation first.
  2. Is the client key trustworthy? Restore addresses only from known proxy ranges; otherwise use the direct source address.
  3. What resource is being exhausted? Choose request limits for application work, connection limits for socket or concurrency pressure, and bandwidth controls for large responses.
  4. Which endpoint needs protection? Start with the expensive or abuse-prone route rather than imposing one number on every URL.
  5. What does normal traffic look like? Measure by endpoint, authentication state, protocol, geography, and shared network before selecting a rate and burst.
  6. Can the change be observed safely? Use dry-run, inspect logs and service metrics, then enforce gradually with a clear rollback.
  7. Did the limit improve service? Confirm lower upstream work and stable legitimate-user success, not merely a higher 4xx count.

NGINX’s strongest DDoS posture is layered: trusted identity restoration, endpoint-specific leaky-bucket request limits, concurrent-connection ceilings, selective bandwidth controls, stream limits for TCP services, continuous observation, and upstream scrubbing for traffic that threatens the network path.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.