You can use Nginx to block and deny access to specific IP addresses or network subnets by adding a deny
directive in your Nginx configuration file. Here’s how to do it:
- Open your Nginx configuration file in a text editor. The file is typically located at
/etc/nginx/nginx.conf
or/etc/nginx/conf.d/default.conf
. - Inside the
http
block, add ageo
block that defines the IP addresses or subnets you want to block:http {
# ...
geo $blocked_ips {
default 0;
1.2.3.4/32 1;
5.6.7.0/24 1;
8.9.10.11 1;
}
}
In this example, we’re defining a
$blocked_ips
variable that is set to1
for the IP addresses or subnets we want to block. Thedefault 0
line sets the variable to0
by default, meaning that IP addresses not explicitly defined in thegeo
block will not be blocked.You can define IP addresses or subnets in CIDR notation (e.g.
1.2.3.4/32
for a single IP address,5.6.7.0/24
for a network subnet, or8.9.10.11
for a single IP address without a subnet). - In your server block or location block, add a
deny
directive that uses the$blocked_ips
variable:server {
# ...
location / {
deny all;
allow 1.2.3.4;
allow 5.6.7.0/24;
allow 8.9.10.11;
# ...
}
}
In this example, we’re denying all access by default using the
deny all
directive, and then using theallow
directive to allow access from specific IP addresses or subnets. Thedeny
directive with the$blocked_ips
variable will block access from IP addresses or subnets defined in thegeo
block. - Save and close the configuration file, and then reload Nginx to apply the changes:
sudo service nginx reload
After reloading Nginx, the specified IP addresses or subnets will be denied access to your website.
Note that this is just one way to block and deny IP addresses or subnets in Nginx, and there are many other ways to do it using Nginx modules or third-party tools. Be sure to test your configuration carefully to ensure that it works as expected, and be aware that incorrectly blocking IP addresses or subnets can have unintended consequences.