Restrict Block Allow IP Addresses in Nginx with Examples

Published on Jun 15, 2022

NGINX can allow or deny access based on a particular IP address or the range of IP addresses of client computers. To allow or deny access, we need to use the allow and deny directives inside the stream context or a server block.

Table of Contents

Allow Deny Syntax

The syntax of allow, deny IP:

server {
  listen 80;

  allow all; # allow all IPs
  deny al; # deny all IPs

  allow IP_ADDRESS; # allow an IP
  allow IP_ADDRESS/24; # allow an IP range

  deny IP_ADDRESS; # deny an IP
  deny IP_ADDRESS/24; # deny an IP range
}

Denying All, Except Certain Addresses

Example of deny all access, except certain addresses:

server {
  listen 80;

  allow 192.168.1.2; # allow single IP
  deny all; # deny all request
}

Deny/Allow a Specific Location

We can deny or allow only a specif location easily:

server {
  listen 80;

  location ^~ /admin { 
    allow 1.2.3.4; 
    deny all;
  }
}

That's all. Thanks for reading. 👍

Comments (0)