How to Block IP Address in NGINX


how to block ip address nginx

Sometimes, you may need to block malicious IP addresses and ranges from your website in order to protect it from attackers. Sometimes, it may be because your website is simply attracting irrelevant audience. Either way, it is easy to block IP address in NGINX.

 

How to Block IP Address in NGINX

Here are the steps to block IP address in NGINX. NGINX provides a module ngx_http_access_module that allows you to easily deny or allow access to specific IP addresses, IP ranges or even domain names.

It supports the following syntaxes:


deny IP;
deny subnet;
allow IP;
allow subnet;
# block all ips
deny all;
# allow all ips
allow all;

You can add multiple rules in your NGINX config file but only the first match will be processed.

 

Here’s how to configure NGINX to block IP addresses.

 

1. Open NGINX config file

Open your NGINX config file in a text editor


$ sudo vim /etc/nginx/nginx.conf

Update the location of NGINX config file according to your requirement.

 

2. Update NGINX config file

Add the following lines, depending on your use case

 

Block an IP from accessing your entire website


location / {
 deny 192.168.1.1;
}

This will block the IP 192.168.1.1 from accessing your entire website.

 

Block an IP from accessing a subdirectory


location /subdirectory/ {
 deny 192.168.1.1;
}

 

Allow an IP address to access your website but block others


location / {
 allow 192.168.1.1;
 deny all;
}

 

Allow an External IP Range to access your website but block others


location / {
 allow 91.68.1.0/24;
 deny all;
}

 

Allow only Intranet/LAN IPs to access your website but block others


location / {
 # allow intranet IPs
 allow 192.168.1.0/24;
 # drop rest of the world
 deny all;
}

Combining Rules

You can also combine rules as shown.


location /wp-admin {
 allow 192.168.1.1;
 deny all;
}

location / {
 deny all;
}

The above code will allow only 192.168.1.1 to access /wp-admin. Everyone else is blocked from accessing any part of your website.

 

Save and close the file.

 

3. Reload NGINX Server

Reload NGINX server to apply changes.


$ sudo service nginx reload

 

 

About Sreeram Sreenivasan

Sreeram Sreenivasan is the Founder of Ubiq, a business dashboard & reporting platform for small & medium businesses. Ubiq makes it easy to build business dashboards & reports for your business. Try it for free today!