Check the below steps to block an IP address:
1. Create a file with the name access.conf in this /nginx/example.com directory.
2. Add the contents from the below sections.
3. Remember to reload Nginx for the changes to take effect.
Command for Blocking an IP from Hitting Your Site:
location / { deny 1.2.3.4; }
This command blocks the IP address of 1.2.3.4 so that no one with this IP address is able to access your site entirely.
Command for Blocking an IP from Hitting a Subdirectory
location /subdirectory/ { deny 1.2.3.4; }
Command to Allow a Single IP while Blocking All Others
In case you want to block access to all IPs but allow a specific IP to still access your site, use the below command:
location / { allow 9.8.7.6; deny all; }
This command is helpful if you’re working on your site and want just you to view it and not others.
Combining Rules
It is also possible to create and combine multiple sets of these rules in your access.conf file:
location /subdir { allow 1.2.3.4; deny all; } location / { deny all; }
With the above command only the IP address 1.2.3.4 will be allowed to browse the subdirectory named /subdir. All other IPs will be blocked from everywhere in your site.
This way you can block IPs with Nginx.