How to Allow Specific IP in Nginx: Simple Guide
To allow a specific IP in
nginx, use the allow directive with the IP address inside a location or server block, followed by deny all; to block others. This setup restricts access so only the specified IP can reach the site or resource.Syntax
The allow directive specifies which IP addresses can access the resource. The deny directive blocks all other IPs not explicitly allowed. These directives are placed inside a server or location block in the Nginx configuration.
Example parts:
allow 192.168.1.100;- permits this IPdeny all;- blocks everyone else
nginx
location / {
allow 192.168.1.100;
deny all;
}Example
This example shows how to allow only the IP 203.0.113.5 to access the entire website, while denying all other IPs.
nginx
server {
listen 80;
server_name example.com;
location / {
allow 203.0.113.5;
deny all;
}
}Output
When a user from IP 203.0.113.5 visits example.com, they see the website normally.
Users from any other IP receive a 403 Forbidden error.
Common Pitfalls
Common mistakes include:
- Placing
allowanddenyoutsideserverorlocationblocks, which makes them ineffective. - Forgetting to reload or restart Nginx after changes, so new rules don't apply.
- Using incorrect IP formats or missing semicolons.
- Not ordering
allowbeforedeny, which can cause unexpected access results.
nginx
location / {
deny all;
allow 203.0.113.5;
}
# This will deny all, including the allowed IP, because deny comes first.
# Correct order:
location / {
allow 203.0.113.5;
deny all;
}Quick Reference
| Directive | Purpose | Example |
|---|---|---|
| allow | Permits access from specified IP or subnet | allow 192.168.0.1; |
| deny | Blocks access from specified IP or all | deny all; |
| location | Defines URL path to apply rules | location /admin/ { ... } |
| server | Defines virtual server block | server { listen 80; ... } |
Key Takeaways
Use
allow to specify permitted IPs and deny all; to block others.Place
allow and deny inside location or server blocks.Always reload Nginx after configuration changes with
nginx -s reload.Order matters:
allow directives must come before deny.Check IP format carefully to avoid access issues.