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 isdeny. 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, standarddeny 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
Whiledeny 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 thedeny 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 samedeny 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, thedeny 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.