How to Make Nginx Ignore Unwanted Requesting IP Addresses

Abstract: Block specific IP addresses or subnets in Nginx to prevent unwanted traffic and malicious actors from reaching your application.

Created: 2026-08-03 by

To block specific IP addresses in Nginx, use the deny directive within your server block or location context. This method is effective for stopping unwanted traffic at the web server level before it reaches your application, providing a critical layer of security against known malicious actors and abusive bots.

Understanding the Deny Directive

Nginx provides a straightforward mechanism to filter incoming requests based on the client's IP address using the built-in access control module. The core command you will utilize is deny. When placed inside a server or location block, this directive instructs Nginx to immediately reject connections from the specified IP or subnet with a 403 Forbidden response. This happens during the initial handshake phase, meaning the backend PHP-FPM processes or upstream servers never even see the request, which saves valuable system resources. It is important to understand that Nginx processes these rules sequentially. If you have multiple deny rules, they are evaluated in order. Furthermore, if you do not explicitly allow certain IPs, Nginx defaults to allowing all traffic unless a deny rule matches. Therefore, structure your configuration carefully to avoid accidentally locking yourself out. For most users, adding these rules directly into the main server block is sufficient, but for more granular control, such as blocking IPs only on specific endpoints, placing them inside a location block is preferable.

Configuring Single IP Blocks

The most common scenario involves blocking a single, static IP address that has been identified as malicious. To achieve this, open your site configuration file, typically located in /etc/nginx/sites-available/ on Debian-based systems or /etc/nginx/conf.d/ on Red Hat-based systems. You need to locate the server block that handles your domain. Inside this block, add the following line:
server {
    listen 80;
    server_name example.com;

    # Block a specific malicious IP
    deny 192.168.1.105;

    location / {
        try_files $uri $uri/ =404;
    }
}
In this example, any request originating from 192.168.1.105 will receive a 403 error. The deny directive accepts both IPv4 and IPv6 addresses. It is crucial to test your configuration after making changes to ensure syntax correctness. You can do this by running nginx -t in your terminal. If the test passes, reload the service using systemctl reload nginx to apply the changes without dropping active connections.

Blocking Subnets and Ranges

Sometimes, a single IP is not enough. Attackers may rotate through a range of addresses belonging to the same provider or network segment. In these cases, you can block an entire subnet using CIDR notation. This is particularly useful when dealing with botnets or spam networks that operate from a specific block of addresses. To block a subnet, append a slash followed by the prefix length to the IP address. For instance, to block the last 256 addresses in a class C network, you would use:
deny 192.168.1.0/24;
This single line effectively denies access to every IP from 192.168.1.0 to 192.168.1.255. Be cautious when using broad subnets, as you might inadvertently block legitimate users who share the same network infrastructure, such as those behind a corporate proxy or a university campus network. Always verify the scope of the block before applying it to a production environment. If you need to manage large lists of IPs, consider using external files with the include directive to keep your main configuration clean.

Handling Proxies and Real Client IPs

A critical consideration when implementing IP blocking is how Nginx determines the source IP. If your server sits behind a reverse proxy, load balancer, or CDN like Cloudflare, the direct connection to Nginx comes from the proxy's IP, not the end-user's. In this setup, standard deny directives will only block the proxy, rendering them useless for filtering actual visitors. To solve this, Nginx must be configured to read the real client IP from headers such as X-Forwarded-For. You can achieve this using the set_real_ip_from and real_ip_header directives. These settings tell Nginx to trust the proxy and update the remote address variable accordingly. Without this configuration, your blocking rules will fail to target the correct entities. Ensure that your proxy is correctly forwarding these headers and that Nginx is configured to recognize them. For more details on isolating services securely, you might want to review our guide on PHP-FPM & Nginx: Security Isolation Not Working, which touches on proper server architecture.

Whitelisting Specific Addresses

While deny blocks traffic, allow permits it. In complex scenarios, you might want to block a large subnet but make an exception for your office IP or a trusted partner. Nginx evaluates allow and deny rules in order, so the last matching rule wins. A common pattern is to allow specific IPs first, then deny the rest of the subnet.
allow 10.0.0.5;
deny 10.0.0.0/24;
In this snippet, 10.0.0.5 is explicitly allowed, while all other IPs in the 10.0.0.x range are denied. This approach ensures that legitimate administrative access is maintained even when broader restrictions are in place. Remember to always whitelist your own IP address to prevent accidental lockouts. If you are migrating from Apache, note that Nginx does not use .htaccess files for dynamic overrides. You must configure these rules directly in the server config. See Improving NFS Server Security on a Local Networks for broader security context.

Frequently Asked Questions

How do I unblock an IP address I previously denied?

Simply remove the deny line associated with that IP from your Nginx configuration file and reload the service. Alternatively, you can add an allow directive for that specific IP, which will override the deny rule if placed correctly in the sequence.

Does Nginx support IPv6 blocking?

Yes, Nginx fully supports IPv6 addressing. You can block IPv6 addresses using the same deny directive, ensuring you use the correct CIDR notation for IPv6 ranges, such as deny 2001:db8::1/64;.

Can I block IPs based on user-agent strings instead?

No, the deny directive only works with IP addresses. To block based on user-agent strings, you must use the if directive combined with $http_user_agent, though this is generally less efficient than IP-based blocking.

What happens if I block my own IP by mistake?

You will lose access to the website via your browser. To regain access, you must connect to the server via SSH and edit the Nginx configuration file to remove or comment out the deny rule, then reload Nginx.

Is it better to block IPs in Nginx or at the firewall level?

Blocking at the firewall level (e.g., iptables or UFW) is more efficient as it drops packets before they reach Nginx, saving CPU cycles. However, Nginx offers easier management for dynamic lists and integrates well with web-specific logic.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More