auth_basic

auth_basic configuration guide for Nginx

auth_basic configuration guide for Nginx

WARNING: make sure you have configured HTTPS for the Nginx server.

Install the apache2-utils package:

sudo apt install apache2-utils

Add a new user to an existing passwords file. Replace username with the desired username:

sudo htpasswd /etc/nginx/passwords username

Alternatively, if a passwords file has not been created, create one and add a user (with the -c flag):

sudo htpasswd -c /etc/nginx/passwords username

Edit the Nginx configuration:

sudo nano /etc/nginx/nginx.conf

Add the following within the server block or location block where you want to protect access:

auth_basic "Authentication Required";
auth_basic_user_file /etc/nginx/passwords;

For example, for a location block:

location /protected {
    auth_basic "Authentication Required";
    auth_basic_user_file /etc/nginx/passwords;
}

Save and exit, then test the Nginx configuration:

sudo nginx -t

Reload Nginx

sudo systemctl restart nginx

# Or, as documented in Nginx Docs
sudo nginx -s reload

Check the status of Nginx:

sudo systemctl status nginx

Optional configurations

Configure a file-sharing folder

Use the following location block:

location /files/ {
    alias /home/user/file_sharing/;
    autoindex on;
    auth_basic "Authentication Required";
    auth_basic_user_file /etc/nginx/passwords;
}

References

ChatGPT

https://www.reddit.com/r/selfhosted/comments/wtsk9x/how_secure_is_nginx_http_basic_authentication/

https://stackoverflow.com/questions/41031810/does-nginx-auth-basic-send-the-password-plaintext

https://docs.nginx.com/nginx/admin-guide/basic-functionality/runtime-control/

Content Licensed under CC BY-SA 4.0. Code licensed under the MIT License.