Control Access in Nginx: IP, Auth, Rate
This article explains how to control access to your nginx web server, covering IP-based allow/deny rules, HTTP basic authentication, and rate limiting. You’ll learn the exact configuration directives, how to combine them, and common pitfalls to avoid.
Why Access Control Matters
Nginx is a high-performance web server and reverse proxy. By default, it serves whatever files are in your root directory to anyone who requests them. Access control lets you restrict who can reach your site or specific parts of it. This is essential for admin panels, staging environments, internal tools, or any content that shouldn’t be public. Without it, sensitive data, configuration files, or application endpoints can be exposed to the internet.
IP-Based Access Control (allow/deny)
The simplest method is to allow or deny requests based on the client’s IP address. This is done with the allow and deny directives, which can be placed in http, server, location, or limit_except contexts. Nginx checks rules in order, and the first match wins. If no rule matches, the default is to allow.
Example: Allow only your office IP to access /admin:
location /admin {
allow 192.168.1.100;
deny all;
}
You can also use CIDR notation for subnets: allow 10.0.0.0/8; or deny 192.168.2.0/24;. For IPv6, use addresses like allow 2001:db8::/32;.
Be careful: if you deny all and then allow a specific IP, the order matters. Always put the allow rules before the deny all. Also remember that IP addresses can be spoofed via headers if nginx is behind a proxy, so this is not a strong security boundary on its own.
HTTP Basic Authentication (auth_basic)
For password protection, nginx uses HTTP Basic Authentication. It’s simple to set up and works with any browser. You need a password file created with the openssl passwd or htpasswd utility (from Apache). The file contains lines like username:hashed_password.
Steps:
- Create a password file, e.g.,
/etc/nginx/.htpasswd. - Add a user:
htpasswd -c /etc/nginx/.htpasswd admin(omit-cfor subsequent users). - In your nginx config, inside the location or server block:
location /private {
auth_basic "Restricted Area";
auth_basic_user_file /etc/nginx/.htpasswd;
}
The auth_basic directive takes a realm name (shown in the browser prompt). The user file path is relative to the nginx prefix (usually /etc/nginx) unless absolute. After changing the config, test with nginx -t and reload. Note that Basic Auth sends credentials in base64 (not encrypted), so always use it over HTTPS.
Rate Limiting (limit_req)
Rate limiting isn’t exactly access control, but it prevents abuse by limiting the number of requests a client can make in a given time. This protects your server from brute-force attacks and DDoS. Nginx uses the limit_req_zone directive to define a shared memory zone, and limit_req to apply it.
Example: Allow 10 requests per second per IP:
http {
limit_req_zone $binary_remote_addr zone=mylimit:10m rate=10r/s;
server {
location /api/ {
limit_req zone=mylimit burst=20 nodelay;
proxy_pass http://backend;
}
}
}
The rate can be r/s (requests per second) or r/m. The burst parameter allows a short queue of excess requests. Without nodelay, excess requests are delayed; with it, they’re processed immediately but the burst is consumed. When the limit is exceeded, nginx returns a 503 by default.
Combining Methods and Common Pitfalls
You can combine IP and auth: first check IP, then require a password. For example:
location /secure {
satisfy any; # or 'all'
allow 192.168.1.0/24;
deny all;
auth_basic "Admin";
auth_basic_user_file /etc/nginx/.htpasswd;
}
The satisfy any means either IP allow OR valid credentials grants access. satisfy all requires both. Common mistakes: forgetting to reload nginx after changes, using the wrong path to the password file, or placing deny all before allow. Also, if you’re behind a reverse proxy (like Cloudflare), the client IP is not the one in $remote_addr; you need to set set_real_ip_from and real_ip_header to get the real visitor IP.
Alternatives and Advanced Options
For more complex access control, consider:
- Access by method: Use
limit_except GET { deny all; }to block POST/PUT on certain URLs. - JWT or OAuth: For APIs, implement token-based auth via Lua (OpenResty) or auth_request to an external service.
- Client certificates: For mutual TLS, use
ssl_verify_clientandssl_client_certificate. - Firewall: For IP blocking, a firewall (like iptables) is often more efficient than nginx for DDoS-scale attacks.
Each has trade-offs in complexity and performance. For most small sites, IP + basic auth is sufficient.
Testing and Troubleshooting
After editing nginx config, always run nginx -t to check syntax. Then reload with nginx -s reload. To test, use curl -I http://yourdomain/private; you should get a 401 if auth is required. For IP rules, try from an allowed and a denied IP. Check the error log (/var/log/nginx/error.log) for messages like “access forbidden by rule” or “no user/password was provided”. If you get a 500, the password file might be unreadable by the nginx user (check permissions).
Frequently Asked Questions
How do I allow multiple IPs in nginx?
Just add multiple allow directives. For example: allow 192.168.1.1; allow 10.0.0.5; then deny all;. Nginx checks each rule in order until a match.
Can I use nginx to password protect a directory without a .htpasswd file?
Nginx requires a password file; you can generate it with openssl passwd -apr1 and manually create the file. There is no built-in user management like Apache’s htpasswd, but the file format is the same.
What is the difference between deny and allow?
allow grants access, deny blocks it. They are evaluated in order, and the first matching rule applies. If no rule matches, the default is to allow.
How do I block an IP in nginx?
Add deny IP_ADDRESS; in the server or location block. For a global block, place it in the http block. Remember to reload nginx.
Does rate limiting stop brute force attacks?
Rate limiting slows them down significantly by limiting attempts per IP, but it doesn’t prevent distributed attacks from many IPs. Combine with fail2ban or a WAF for better protection.
Why am I getting 403 Forbidden when I try to access a location?
Check if you have a deny all rule that matches your IP, or if the file permissions are incorrect. Also, ensure the index file exists and is readable. The error log will show the exact reason.
Related
Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.