Contents

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.

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.

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
Note

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
  • 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.