0
0
NginxHow-ToBeginner · 3 min read

How to Block IP Address in Nginx: Simple Guide

To block an IP address in nginx, use the deny directive inside the server or location block. For example, deny 192.168.1.1; will block that IP from accessing your site.
📐

Syntax

The deny directive tells Nginx to block requests from specified IP addresses or ranges. It is used inside server or location blocks. The allow directive can be used to permit specific IPs. The order matters: Nginx checks allow and deny rules in order.

nginx
deny 192.168.1.1;
allow all;
💻

Example

This example blocks the IP address 203.0.113.5 from accessing the entire website. All other IPs are allowed.

nginx
server {
    listen 80;
    server_name example.com;

    deny 203.0.113.5;
    allow all;

    location / {
        root /var/www/html;
        index index.html;
    }
}
Output
When a user from IP 203.0.113.5 tries to access the site, Nginx returns a 403 Forbidden error. Other users can access normally.
⚠️

Common Pitfalls

  • Placing deny outside server or location blocks causes errors.
  • Not ordering allow and deny correctly can block all users unintentionally.
  • Forgetting to reload Nginx after changes means the block won't apply.
nginx
server {
    listen 80;
    server_name example.com;

    allow all;
    deny 203.0.113.5;

    location / {
        root /var/www/html;
    }
}

# This order blocks the IP 203.0.113.5 because 'deny' overrides 'allow all' when placed after it.

# Correct order:
server {
    listen 80;
    server_name example.com;

    deny 203.0.113.5;
    allow all;

    location / {
        root /var/www/html;
    }
}
📊

Quick Reference

DirectivePurposeExample
denyBlocks access from specified IP or rangedeny 192.168.1.1;
allowAllows access from specified IP or rangeallow 10.0.0.0/24;
orderControls evaluation order (legacy, avoid in new configs)N/A
reloadApply changes after editing configsudo nginx -s reload

Key Takeaways

Use the deny directive inside server or location blocks to block IPs.
Order of allow and deny directives matters; deny should come before allow.
Always reload Nginx after changing configuration to apply blocks.
Blocking IPs returns a 403 Forbidden error to blocked users.
Test your configuration with nginx -t before reloading to avoid errors.