Restrict Block Allow IP Addresses in Nginx with Examples

Jun 15, 2022 · Article · 2 min, 419 words

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; # 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 { 
    deny all;

That's all. Thanks for reading. 👍


No comments yet…