nginx: blocking access from certain IPs (ngx_http_access_module)

Practice



How can you block access to a specific site or to all sites on a given server for selected (specified) IP addresses?

nginx has a built-in module, "ngx_http_access_module", which handles exactly this. You don't need to install anything extra — the module comes out of the box.


Syntax

The module has only two directives: allow and deny.
  • The allow directive permits access from the specified IP.
  • The deny directive, accordingly, denies access.

The module reads the rules one after another from top to bottom, and the first matching rule stops further analysis of the rules. Thus, if the module finds that the current IP address matches the rule being examined, it will execute the allow or deny action, and all rules following the matched one will be ignored.

Here's an example — we allow access from address 192.168.0.5, but deny access from the entire rest of the 192.168.0.0/24 subnet:
Allow 192.168.0.5;
Deny 192.168.0.0/24;

It might seem that the "C" network 192.168.0.0/24 is fully denied by the second rule, and address 192.168.0.5 falls within this network — so it would also be denied. But no, because its rule comes before the rule denying the whole network, so it is specifically 192.168.0.5 that will be allowed to keep working, while everyone else from that C network won't.


And here's an example of a rule where access is allowed only for certain IP addresses:
allow 192.168.0.1;
allow 192.168.0.2;
allow 192.168.1.0/24;
deny all;


The word all, as you've already guessed, means "all addresses".


Blocking access to all sites on the server

To do this, open the nginx.conf file for editing and add the necessary rules to the http{} section. For example, at the end of the section. This way you'll apply the rules to the entire server, i.e. all the sites it serves.


Blocking individual sites

In this case you should open the configuration files of the desired sites (for example, from the sites-enabled/ directory) and add allow or deny directives to the server{} section.


Blocking individual parts of a site

To do this, open the configuration files of the desired sites and add blocking directives to the location {} sections.

Applies to: nginx

Comments

To leave a comment

If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Lectures and tutorial on "Running server side scripts using PHP as an example (LAMP)"

Terms: Running server side scripts using PHP as an example (LAMP)