Securing Directories with Nginx Basic Auth

Posted on Oct 14, 2025

Protecting Your Web Content

Sometimes you have content on your website that you don’t want to be publicly accessible. Whether it’s a private section for family and friends, or a staging area for a new project, Nginx’s basic authentication is a simple and effective way to password-protect parts of your site.

In this post, we’ll walk through how to protect a directory called /private and everything inside it.

1. Creating the Password File

First, we need to create a .htpasswd file that will store our username and password. The password needs to be encrypted. We can use the htpasswd command-line tool for this. If you don’t have it, you can usually install it with apache2-utils.

Let’s create a file with the username private and the password secret. The -c flag creates a new file. For subsequent users, you would omit this flag.

htpasswd -c /etc/nginx/.htpasswd private

You will be prompted to enter the password. Type secret and press enter.

The resulting /etc/nginx/.htpasswd file will contain a line similar to this:

private:$apr1$bJ.6g.8B$Z3gO8v.A.d5a.r/2zI3Ea/

2. Configuring Nginx

Now, we need to tell Nginx to protect the /private location. We do this by adding a location block to our server configuration.

Here’s an example of what your Nginx configuration might look like. This assumes your website files are served from /var/www/html.

server {
    listen 80;
    server_name your_domain.com;
    root /var/www/html;

    # This is the public part of your site
    location / {
        try_files $uri $uri/ =404;
    }

    # This is the protected directory
    location /private {
        auth_basic "Restricted Content";
        auth_basic_user_file /etc/nginx/.htpasswd;
        try_files $uri $uri/ =404;
    }
}

Let’s break down the important parts:

  1. location /private: This tells Nginx to apply these rules to any request that starts with /private.
  2. auth_basic "Restricted Content": This sets the message that will be displayed in the password prompt.
  3. auth_basic_user_file /etc/nginx/.htpasswd: This tells Nginx where to find the password file.

3. Reloading Nginx

After you’ve saved your configuration, you need to reload Nginx for the changes to take effect.

sudo systemctl reload nginx

Now, if you try to access http://your_domain.com/private in your browser, you’ll be prompted for a username and password.

That’s it! You’ve successfully secured a directory on your website.