Basic Authentication in Nginx β Protect Your Website with a Password

Sometimes you need to restrict access to specific areas of your websiteβsuch as an admin panel, staging environment, or internal documentation. One of the simplest ways to do this is by enabling Basic Authentication using Nginx. In this guide, youβll learn how to set up password protection in just a few steps.
π§ Nginx Configuration Example with Basic Auth
server {
server_name site.com;
location / {
...
auth_basic "Administrator Area";
auth_basic_user_file /etc/nginx/protections/site.com.htpasswd;
...
}
}
auth_basic
sets the authentication prompt message (realm).auth_basic_user_file
specifies the path to the password file.
π Installing Utilities & Creating a Password File
First, install the tool that allows you to create .htpasswd files:
sudo apt-get install apache2-utils
Now create a new password file and add the admin user:
htpasswd -c site.com.htpasswd admin
The -c
flag creates a new file, overwriting it if it exists. Don’t use -c
when adding additional users.
Move the file to your desired location, such as:
sudo mv site.com.htpasswd /etc/nginx/protections/
Make sure to test your Nginx configuration and reload it:
sudo nginx -t
sudo systemctl reload nginx
β Best Practices for Security
Store the .htpasswd file outside the publicly accessible directories.
For more robust authentication, consider using OAuth, JWT, or integration with a centralized identity provider.
Donβt forget to enforce HTTPS to protect credentials during transmission.