Password protecting a directory with htaccess and htpasswd

Password Protecting a web directory with htaccess

Password protecting a web directory can help make a directory private and only accessible to one or several persons that have the username(s) and password(s).
htaccess

 

How to password protect a directory?

htaccess

  1. Go to the directory you want protected.
  2. Check if you have a .htaccess file.
  3. If a htaccess file is available, you have to edit it, otherwise create a new .htaccess file.
  4. Add the following to the htaccess file:
AuthUserFile /home/linuxuser/.htpasswd
AuthType Basic
AuthName “Tech and Dev Example”
Require valid-user

AuthUserFile: this is the path of the .htpasswd file where the username and password will be stored. The file can be located anywhere, but ideally, it’s better if it’s placed in a non public directory where users can’t access it from the web.

AuthType: should be Basic

AuthName: The title of the window that will be authenticating the user. For example if you’re password protecting your private files, you might want to change this to “My Private Files”.

 

htpasswd

This is the file where the username and password are stored.
This file is usually called htpasswd (by convention if you want), however you can rename this file to anything you want. Many applications use their appname followed by htpasswd, for example .awstats-htpasswd
It’s always a better idea to keep this file outside of the public folder (www or public_html…)
Assuming you want the username to be username and the password to be password, write the following command in SSH:
#htpasswd -nb username password
Then inside the htpasswd file write the output value from the SSH (the password might be different since everytime a different salt value is used):
username:60lwxfC9Ln84g
You can add as many usernames and passwords as you like, for example:
username:60lwxfC9Ln84g
username2:30dJVEURUeYJc

 

How is the password getting encrypted?

To understand more on how the password is generated and encrypted, you can check my previous post: Understanding the encryption process in htpasswd file.
To generate a username/password, you can check our online Encryption Tools.

 

Example

http://lab.tech-and-dev.com/protecteddir/
Username: username
Password: password
or
Username: username2
Password: password2

Any questions or suggestions? Please leave a comment below!

 

Leave a Reply

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