Nginx – IP based access control


Nginx comes with a nifty module that allows us to allow or deny access to directories served by the webserver. The module is named ngx_http_access_module to allow or deny access to IP address. The syntax can look as follows:

The rules are checked in sequence from top to bottom until the first match is found.In the above example subnets and are allowed with the exception of

IPv6 range 2001:0db8::/32 is also allowed, rest of the world is denied access.

How do I use this to secure my website?

Your access list should be included in the nginx.conf file but I never add the IP directly into that file, instead I create a blocklist file with all the IP’s that I want to block or allow and include this file into the nginx.conf file.

That way I can add the file without being root and the file is checked every time a user tries to access the website.

Here goes, first of we need to edit the nginx.conf file once and for all.

 Find the http sectionand add the following lines inside that block

Save and exit with Ctrl+X

Time to create the include file itself.

add IPs as you wish, if there is no explicit deny row, it will allow the connection:

if you want it to work the other way around and deny everyone that is NOT explicitly allowed in the file you could add these lines:

When you are done, Save and Exit with Ctrl+X.

test the configuration for spelling errors other configuration errors with:

If you get an error message, troubleshoot the error and test again until everything is fine.

Reload the configuration with:

Try it out from different IPs and see the difference.

Customize the HTTP 403 Forbidden Error Message

The default 403 error page is pretty boring so let us create something a little nicer.

create a html file in your webroot folder that we should load when the error occurs, paste this into the file:

then edit your Nginx config file and add this

inside the server block. The example above tells Nginx to display the file error403.html everytime a 403 error occurs. We do need to make the exemption in the configuration file that everyone will be allowed to read this file, otherwise a default 403 error page would be shown.

From now on you know how to easily block access to your website and only allow a few selected IPs.


1 comment for “Nginx – IP based access control

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.