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.confor/etc/nginx/conf.d/default.conf. - Inside the
httpblock, add ageoblock 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_ipsvariable that is set to1for the IP addresses or subnets we want to block. Thedefault 0line sets the variable to0by default, meaning that IP addresses not explicitly defined in thegeoblock will not be blocked.You can define IP addresses or subnets in CIDR notation (e.g.
1.2.3.4/32for a single IP address,5.6.7.0/24for a network subnet, or8.9.10.11for a single IP address without a subnet). - In your server block or location block, add a
denydirective that uses the$blocked_ipsvariable: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 alldirective, and then using theallowdirective to allow access from specific IP addresses or subnets. Thedenydirective with the$blocked_ipsvariable will block access from IP addresses or subnets defined in thegeoblock. - 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.