Mahdi.Kh
September 21, 2026
Sometimes we need to restrict access to certain paths using a password. In this part, we learn how to create this password and use it.
To set a password on a path, we can use a combination of the auth_basic and auth_basic_user_file directives.
The auth_basic directive specifies a text that's shown to the user on the password entry page. The auth_basic_user_file directive specifies the path of the file that holds the username and password. To create a file that holds the username and password, you can use the htpasswd tool.
In the command above, we set the username to admin and the password to pass123. The -c flag creates a .htpasswd file, and the -b flag lets us put the password right in the command itself. If we don't use the -b flag, we'll be asked for the password separately. This flag is typically useful when we want to put this command inside our own code and don't intend to type the password in manually.
If the file already exists, we can also add a new username and password to it:
Then we can protect the path we want with the settings below:
Following the example above, if we go to the /secure path, the browser will ask us for a username and password, and if we enter them correctly, the page we wanted is shown to us.
Some browsers ignore the text we specify using the auth_basic directive. For example, Chrome and Firefox don't display this text.
If we enter the username and password correctly, we won't be asked for them again for a short while.
To create the file that holds usernames and passwords, we can also use the openssl passwd command. For more information, you can check the nginx documentation.
Previous part: Redirect and Rewrite | Nginx from Scratch
Next part: Blocking and Whitelisting IPs | Nginx from Scratch