How to Password Protect a Directory in Nginx

Last updated on

In this guide we will set up password authentication for Nginx to password protect a web directory.

We will first install apache2-utils, which can generate the .htpasswd file that works with both Nginx and Apache.

sudo apt-get install apache2-utils

Once installed, we can name generate the .htpasswd file. Simply change username to the username you require. Generate a password and keep it safe.

sudo htpasswd -c /etc/nginx/.htpasswd username

There should now be a .htpasswd file containing your username and encrypted password. You can check with:

cat /etc/nginx/.htpasswd

We now need to add two directives to our Nginx configuration file. The location of the config file may vary depending on your setup, though the default is usually in /etc/nginx/sites-available/default.

sudo nano /etc/nginx/sites-available/default

If you want to password protect the entire domain, look for the location block and add two new directives marked in red below.

. . .
location / {
        # First attempt to serve request as file, then
        # as directory, then fall back to displaying a 404.
        try_files $uri $uri/ =404;
        auth_basic "Restricted Access";
        auth_basic_user_file /etc/nginx/.htpasswd;
. . .

Save file and exit (press CTRL + X, press Y and then press ENTER).

Check that the Nginx config file is valid.

sudo nginx -t

If valid, reload Nginx config.

sudo service nginx reload

You can now open the web directory in your browser and you should be prompted to enter a password.

If you want to password protect a particular folder, you will need to create a new location block underneath the original.

This example below will protect the directory called /test.

. . .
location /test {
        auth_basic "Restricted Access";
        auth_basic_user_file /etc/nginx/.htpasswd;
. . .

Let me know if this helped. Follow me on Twitter, Facebook and YouTube, or 🍊 buy me a smoothie.

Leave a reply

Your email address will not be published. Required fields are marked *