ittavern.com/items/2022-12-11_long_nginx-simple-and-native-authentication-function.md
2025-10-27 20:12:00 +01:00

74 lines
2.3 KiB
Markdown

# 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:
```markdown
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:
```markdown
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:
```markdown
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](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:
```markdown
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:
```markdown
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.
---