How to block an IP address in Nginx

Published on: (Updated on: )
Blocking an IP address or a range of IP addresses using Nginx involves modifying the Nginx configuration file for your server block (often found in '/etc/nginx/sites-available/' directory on Linux systems).
Here's how to block specific IPs:
1. Single IP Address Blocking
If you want to block a specific IP address, add the deny directive to the server section of your nginx configuration file like in the example below:
location / {
deny 123.45.67.89; // this directive will block the provided IP address, in this case (123.45.67.89). Replace the IP address with the one you wish to block.
allow all; // this would allow all other IP address. This line is optional because other IPs would usually be allowed unless specifically blocked.
}
2. Blocking Multiple IP Addresses
If you want to block multiple specific IP addresses, you can add a 'deny' line for each IP address like so:
location / {
deny 123.45.67.89;
deny 98.76.54.32;
}
3. Blocking an IP Range
If you want to block a range of IP addresses, you can use Classless Inter-Domain Routing (CIDR) notation. For example, to block a range of IPs from '123.45.67.0' to '123.45.67.255':
location / {
deny 123.45.67.0/24;
}
Steps to Apply the Changes
After making the changes, you will need to:
- Save your configuration file. Make sure you edit the file with root permissions (using sudo if necessary).
- Test the Nginx configuration for syntax errors by running:
sudo nginx -t
- Reload Nginx to apply the changes without downtime:
sudo systemctl reload nginx
Or restart Nginx (this might cause brief downtime):
sudo systemctl restart nginx
Important Considerations:
- Location of 'deny' and 'allow' Directives: While the example uses the 'location / { ... }' block to apply the IP bans to the entire site, you can also use these directives within other `location` blocks or the `server` block as needed.
- Order Matters: The `order` of `allow` and `deny` directives is essential. Typically, Nginx processes these rules sequentially and follows a "last match wins" logic.
- Avoiding Unintended Blocks: Be cautious when blocking IP ranges, as this can potentially block legitimate users.
- Dynamic IPs: Keep in mind that if the user you're trying to block has a dynamic IP address (changes frequently), blocking their IP might only be a temporary solution.
Remember, IP-based blocking is most effective against basic attacks or nuisances. More sophisticated abusers often find ways around IP blocks, such as using VPNs, proxies, or botnets with diverse IP ranges.