0
0
NginxHow-ToBeginner · 3 min read

How to Use Allow and Deny Directives in Nginx for Access Control

In Nginx, use the allow directive to permit access from specific IP addresses or networks, and the deny directive to block access. These directives are placed inside a location or server block to control who can reach your site or resources.
📐

Syntax

The allow and deny directives control access by IP address or network. You place them inside server or location blocks.

  • allow <IP_or_network>; — permits access from the specified IP or network.
  • deny <IP_or_network>; — blocks access from the specified IP or network.
  • allow all; — allows access from all IPs.
  • deny all; — denies access from all IPs.

Order matters: Nginx checks these rules top to bottom and stops at the first match.

nginx
location / {
    allow 192.168.1.0/24;
    deny all;
}
💻

Example

This example allows access only from the local network 192.168.1.0/24 and blocks everyone else.

nginx
server {
    listen 80;
    server_name example.com;

    location / {
        allow 192.168.1.0/24;
        deny all;
        root /var/www/html;
        index index.html;
    }
}
Output
When a user from 192.168.1.x visits example.com, they see the website normally. Users from other IPs get a 403 Forbidden error.
⚠️

Common Pitfalls

Common mistakes include:

  • Placing allow and deny outside server or location blocks, which makes them ineffective.
  • Using deny all; before allow rules, which blocks everyone because order matters.
  • Not specifying networks correctly (e.g., missing CIDR notation).

Always put allow rules before deny all; to whitelist IPs.

nginx
location / {
    deny all;
    allow 192.168.1.0/24;
}

# This blocks everyone because deny all is checked first.
📊

Quick Reference

DirectivePurposeExample
allowPermit access from IP or networkallow 10.0.0.0/8;
denyBlock access from IP or networkdeny 192.168.0.1;
allow allAllow all IPsallow all;
deny allDeny all IPsdeny all;

Key Takeaways

Use allow to permit and deny to block IP addresses or networks in Nginx.
Place allow and deny inside server or location blocks for them to work.
Order matters: Nginx stops checking rules after the first match, so put allow before deny all; to whitelist IPs.
Incorrect order or placement can block all users unintentionally.
Use CIDR notation to specify IP ranges correctly.