NGINX: HTTP basic authentication

The ngx_http_auth_basic_module module allows limiting access to resources by validating the user name and password using the “HTTP Basic Authentication” protocol.
Access can also be limited by address. Simultaneous limitation of access by address and by password is controlled by the satisfy directive.
Add the following to the vhost config file to limit access:

location / {
    auth_basic           “Restricted access";
    auth_basic_user_file /etc/nginx/passwords/passwords;
}

This enables validation of user name and password using the “HTTP Basic Authentication” protocol. The specified parameter is used as a realm. The special value off cancels the effect of the auth_basic directive inherited from the previous configuration level.
Specifies a file that keeps user names and passwords, in the following format:

# comment
name1:password1
name2:password2:comment
name3:password3

The following password types are supported:

  • encrypted with the crypt() function; can be generated using the “htpasswd” utility from the Apache HTTP Server distribution or the “openssl passwd” command;
  • hashed with the Apache variant of the MD5-based password algorithm (apr1); can be generated with the same tools;

Create password for first user:

htpasswd -c /etc/nginx/passwords/passwords paul

To add an additional user:

htpasswd /etc/nginx/passwords/passwords pierre

To allow per adddress:

location / {
    deny  192.168.1.1;
    allow 192.168.1.0/24;
    allow 10.1.1.0/16;
    allow 2001:0db8::/32;
    deny  all;
}

Allows access if all (all) or at least one (any) of the ngx_http_access_module, ngx_http_auth_basic_module, ngx_http_auth_request_module, or ngx_http_auth_jwt_module modules allow access.

location / {
    satisfy any;
    allow 192.168.1.0/24;
    allow 10.0.X.0/24;
    deny  all;

    auth_basic           "closed site";
    auth_basic_user_file conf/htpasswd;
}

Source: https://nginx.org/en/docs/http/ngx_http_auth_basic_module.html
Source: https://nginx.org/en/docs/http/ngx_http_access_module.html

Leave a Reply