Skip to main content

Configuring Access Control

1. Allowing IP Addresses

Directive Values Description
allow IP or CIDR Allows access from specified IP address or network range
deny IP or CIDR Denies access from specified IP address or network range

Example: Allow specific IP address

location / {
    allow 192.168.1.100;
    deny all;
}

Example: Allow IP range using CIDR

location / {
    allow 192.168.1.0/24;
    deny all;
}
Note: The allow and deny directives are processed in the order they appear. The last matching directive wins.

2. Denying IP Addresses

Directive Values Description
deny ip-address Deny access to a specific IP address or subnet
allow ip-address Allow access to a specific IP address or subnet

Example: Deny specific IP address

server {
    listen 80;
    server_name example.com;

    deny 192.168.1.100;
    allow all;
}

Example: Deny IP range

server {
    listen 80;
    server_name example.com;

    deny 192.168.1.0/24;
    allow all;
}
Note: The deny and allow directives are processed in order, with the last matching rule taking effect. If no rules match, access is denied by default.

3. Using CIDR Notation

IP Range CIDR Notation Number of Addresses Example Usage
192.168.1.0 - 192.168.1.255 192.168.1.0/24 256 Allow access to local network
10.0.0.0 - 10.0.0.255 10.0.0.0/24 256 Allow access from private subnet
172.16.0.0 - 172.31.255.255 172.16.0.0/12 1,048,576 Allow access from private network range
203.0.113.0 - 203.0.113.3 203.0.113.0/30 4 Allow access to specific IP block

Example: Restricting Access by CIDR

location /admin {
    allow 192.168.1.0/24;
    allow 10.0.0.0/8;
    deny all;
}

4. Setting Allow/Deny Order

Directive Values Description
allow ip-address | cidr | all Allows access from specified IP or network
deny ip-address | cidr | all Denies access from specified IP or network

Example: Basic allow/deny configuration

location / {
    allow 192.168.1.0/24;
    deny all;
}
Note: The order of allow and deny directives matters. Nginx processes them in the order they appear in the configuration file.

Order of Processing

  • Nginx evaluates allow and deny rules sequentially
  • First matching rule wins
  • If no rules match, access is denied by default (unless allow all is specified)

5. Implementing HTTP Basic Auth

Directive Description Example
auth_basic Enables HTTP Basic Authentication auth_basic "Restricted Area"
auth_basic_user_file Specifies the file containing user credentials auth_basic_user_file /etc/nginx/.htpasswd

Example: Basic Auth Configuration

location /admin {
    auth_basic "Admin Area";
    auth_basic_user_file /etc/nginx/.htpasswd;
}
Note: The .htpasswd file should be stored outside the web root for security.
Warning: HTTP Basic Auth sends credentials in base64-encoded form; it should not be used over unencrypted connections.

6. Setting Auth User File

Directive Values Description
auth_basic string Enables basic authentication and sets the realm name for the protection.
auth_basic_user_file file_path Specifies the path to the file containing user credentials in htpasswd format.

Example: Basic Authentication Setup

location /admin {
    auth_basic "Admin Area";
    auth_basic_user_file /etc/nginx/htpasswd;
}
Note: The htpasswd file must be created using the htpasswd utility or manually formatted with username:encrypted_password pairs.
Warning: Basic authentication is not secure over HTTP. Always use HTTPS to protect credentials in transit.

7. Creating htpasswd File

Use the htpasswd utility to create and manage user credentials for HTTP basic authentication.

Command Description Notes
htpasswd -c /path/to/.htpasswd username Create a new htpasswd file with a user Use -c flag for creation; prompts for password
htpasswd /path/to/.htpasswd username Add a new user to an existing htpasswd file Does not overwrite the file
htpasswd -D /path/to/.htpasswd username Remove a user from the htpasswd file Deletes the specified user

Example: Creating htpasswd File

htpasswd -c /etc/nginx/.htpasswd admin
New password: ********
Re-type password: ********

Example: Adding User to Existing File

htpasswd /etc/nginx/.htpasswd user1
New password: ********
Re-type password: ********
Note: The htpasswd utility is part of the Apache HTTP Server tools. Ensure it's installed on your system (e.g., via apt install apache2-utils on Debian/Ubuntu).
Warning: Store the htpasswd file outside the web root to prevent unauthorized access.

8. Using Auth Request Module

Directive Description Values Notes
auth_request Specifies the URI to which the request should be forwarded for authentication /auth Must return a 200 status for successful authentication
auth_request_set Sets a variable from the response of the auth request $auth_resp_header Can be used to pass data from auth server to the main request
auth_request_user_info Enables passing user info to the auth server on, off Defaults to off

Example: Basic auth request configuration

location /protected {
    auth_request /auth;
    proxy_pass http://backend;
}

location = /auth {
    internal;
    proxy_pass http://auth-service;
    proxy_set_header Host $host;
}

Example: Setting variables from auth response

location /secure {
    auth_request /auth;
    auth_request_set $user_id $upstream_http_user_id;
    proxy_pass http://backend;
}
Note: The auth_request directive is part of the ngx_http_auth_request_module, which is not included in the standard Nginx build. It must be compiled with the --with-http_auth_request_module option.
Warning: If the auth server returns a non-200 status, Nginx will return an error (typically 403 or 401) to the client. Ensure that your auth server correctly handles all authentication scenarios.

9. Configuring Satisfy Directive

Directive Values Description
satisfy all | any Determines whether all or any of the access control rules must be satisfied.

Example: Using satisfy any

location /admin {
    satisfy any;
    allow 192.168.1.0/24;
    auth_basic "Admin Area";
    auth_basic_user_file /etc/nginx/htpasswd;
}
Note: When satisfy any is used, access is granted if any of the allow or deny directives match. When satisfy all is used, all matching rules must pass for access to be granted.

10. Restricting by User Agent

Directive Description Values Notes
valid_user_agents Defines a list of valid user agents string Can be used with user_agent variable
if ($http_user_agent ~* "bot") Conditionally restricts access based on user agent regex Matches case-insensitive user agent strings

Example: Restricting access by user agent

location / {
    if ($http_user_agent ~* "bot") {
        return 403;
    }
}

Example: Allowing only specific user agents

location / {
    set $allowed 0;
    if ($http_user_agent ~ "Chrome") {
        set $allowed 1;
    }
    if ($http_user_agent ~ "Firefox") {
        set $allowed 1;
    }
    if ($allowed = 0) {
        return 403;
    }
}

11. Implementing Token-based Authentication

Directive Description Values Notes
auth_jwt Enables JWT-based authentication on | off Must be set in the http, server, or location context
auth_jwt_key_file Path to the file containing the public key for JWT verification /path/to/public/key.pem Required when using auth_jwt
auth_jwt_token Specifies the name of the header or cookie containing the JWT token Authorization Defaults to Authorization with Bearer prefix
auth_jwt_realm Realm used in the WWW-Authenticate response api Used for client-side error handling

Example: Basic Token Authentication Setup

location /api/ {
    auth_jwt "API Access";
    auth_jwt_key_file /etc/nginx/jwt/public.key;
    proxy_pass http://backend;
}

Example: Token Authentication with Custom Header

location /secure/ {
    auth_jwt "Secure Area";
    auth_jwt_key_file /etc/nginx/jwt/public.key;
    auth_jwt_token "X-API-Token";
    proxy_pass http://backend;
}
Note: JWT tokens must be signed with the private key corresponding to the public key specified in auth_jwt_key_file.
Warning: Ensure that the auth_jwt_key_file is not accessible via HTTP to prevent token forgery.

12. Using Subrequest Authentication

Directive Description Values Notes
auth_request Specifies the URI to which the request is sent for authentication /auth Must return a 200 status for successful authentication
auth_request_set Sets a variable to the value of a header from the auth response $auth_header Can be used to pass auth data to the main request
auth_request_background Enables background authentication for better performance on, off Defaults to off; set to on for async auth

Example: Basic auth_request usage

location /protected {
    auth_request /auth;
    proxy_pass http://backend;
}

Example: Setting auth headers with auth_request_set

location /protected {
    auth_request /auth;
    auth_request_set $auth_user $upstream_http_x_user;
    proxy_pass http://backend;
}
Note: The auth_request directive is processed before the main request, and any headers set by auth_request_set are available in the main request context.
Warning: If the auth endpoint returns a 401 or 403, Nginx will return that status code to the client. Ensure your auth endpoint handles errors gracefully.

Was this article helpful?