Protect web directory with .htaccess, and .htpasswd
This post is also available in: English
Password protect one or more directories with Basic HTTP Authentication using
.htaccess. And a
.htpasswd file will be used to store login details. There are many online tools to generate the
.htpassswd and .htaccess.
Or just simply create a
.htaccess file with below text by copy/paste:
AuthName “My Protected Area”
Htpasswd Generator – Create htpasswd
Use the htpasswd generator to create passwords for htpasswd files.
Just enter username and password and an entry for a htpasswd file is generated. You can use the htaccces Authentication generator to create a htaccess file that will password protect your site or a directory. This htpasswd generator creates passwords that are hashed using the MD5 algorithm, which means that you can use it for sites hosted on any platform, including Windows and Linux. You can also create htpasswd passwords with PHP on your own server – this technique only works on Linux though. Read more about htpasswd files.
Above text for authenticating with username is
ubuntu, and password is
htpasswd – The file to store passwords
Htpasswd files are used when password protecting a website or a directory using HTTP Authentication and Apache’s htaccess files.
The htpasswd file contains username in plain text (unencrypted) and a hashed (encrypted) password. Here’s an example:
Each line contains a username and a password separated by a colon “:”. You can not see the actual passwords as they are hashed (encrypted) using a complex algorithm. The default algorithm is different from platform to platform. On Windows the passwords are hashed using MD5, and on Linux its based on a system function called “crypt()”. The htpasswd generator on this site uses MD5 which means that the hashed passwords can be used on both Windows and Linux.
Normally the htpasswd file is named .htpasswd, but you are actually free to name your password file what every you like. It is perfectly valid to use a name like “passwords.txt” which may seem more appealing to Windows users. However there is one catch. Apache is usually configured to prevent access to .ht* files – starting with “.ht”. If you name your password file “passwords.txt”, a user can access it, and retrieve all valid usernames. Since the passwords are hashed he can’t use them directly, but it will help him gain access using brute force.
It is therefore recommended to name a password file .htpasswd.
Hashed passwords can be generated with the command-line tool htpasswd (htpasswd.exe on Windows) which is part of a normal Apache installation. You can also create passwords using the htpasswd generator on this site, or create passwords yourself using PHP.