NGINX Blacklist IPs and Subnets

The ideal way to blacklist is at the router or firewall level. However there is an option to whitelist or blacklist using NGINX.

I use the following site to get a list of dodgy IP's http://rules.emergingthreats.net/fwrules/emerging-Block-IPs.txt

Copy and Paste that txt file into Notepad++

We now need to change the formatting for NGINX.

In Notepad ++ press Ctrl + H - this will open the replace menu.

enter image description here

Enter the details above.

  • Find What - ^
  • Make sure to have a space after the 'DENY'.
  • Click 'Replace All'.

And then use the details below,

enter image description here

  • Find What - $
  • Replace with - ;
  • And then 'Replace All'

Save the file as blacklist.conf and save it in the NGINX Conf folder.

Finally add this to the NGINX.conf in the HTTP Block

include blacklist.conf;

Restart NGINX and now all the IPs and Subnets listed will be blocked. Anyone trying to access your server from a blocked IP will get a HTTP 403 error, Access forbidden.