Skip to main content

nginx - simple and native authentication function

Important disclaimer: This solution is not secure! - It is fine for a quick and temporary solution for your local network, but it is not a secure solution for important ressources that are available over the internet.

As a side note: without TLS (HTTPs), the credentials will be sent in plain text, and are easily accessable.

Creating the user

Even though you could do it per hand, it is recommended to use the Apache utility to create the user.

The package needed is called apache2-utils for Debian derivatives and httpd-tools for RHEL derivatives.

sudo htpasswd -c /etc/nginx/htpasswd AzureDiamond # The username is case-sensitive and the path and name of the password file can be changed

Now it is time to choose a secure password:

New password:
Re-type new password:
Adding password for user AzureDiamond

You now can find the password file with the hashed password in the location of your choice:

cat /etc/nginx/htpasswd
AzureDiamond:$apr1$8xZ0m9Yq$NVBN9veofzoV9vBoBK7z40

Side note: You can remove a user with the following command:

sudo htpasswd -D /etc/nginx/htpasswd AzureDiamond # remember to choose the correct file

Change your nginx config

We can now add 2 line to our server or location segment to activate the authentication feature:

auth_basic "You shall not pass!";
auth_basic_user_file /etc/nginx/htpasswd;

Check the nginx config with sudo nginx -t and if it confirms the correct syntax, restart the nginx service with sudo systemctl restart nginx.

You can test it here: https://ittavern.com/azurediamond

Exclude subdirectories

If you, for example, add the authentication to the root directory of your site, you can exclude chosen subdirectories by adding the following line to the location segment:

location /api/ {
        auth_basic off;
}

White- / blacklist IPs

More step further, just work with white- and blacklists by adding chosen IPs like this to the chosen segment:

    deny  8.8.8.8;
    allow 9.9.9.9;
    allow 10.10.10.0/24;
    deny  all;

Special thanks to ruffy, for informing me about the processes behind it and the security risks.


E-Mail hellofoo@ittafoovern.comcom


More reading: