Set up Password Authentication with Nginx

December 24, 2022 Reading time: ~1

In this guide, i will demonstrate how you can password protect sections of your site on an Nginx web server.

First you need to create the file that will hold our username and password.

Install the apache2-utils package on your server:

$ sudo apt-get install apache2-utils

Now use the command to create a new entry in your password file:

$ sudo htpasswd -c /etc/nginx/.htpasswd nfcg

You will be asked to supply and confirm a password.

To set up authentication add the code below inside your server block.

    location / {

        try_files $uri $uri/ =404;

        auth_basic "Restricted Access";

        auth_basic_user_file /etc/nginx/.htpasswd;

    }

Save the file and restart Nginx.

$ sudo service nginx restart

The directory you specified is now password protected.

About

Welcome to my blog. I'm a technology enthusiast. I will use this space to present my projects and post simple tips on computer technology and programming.

Tags