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).