Let's check how to add password protection to directories, there are many ways to add password protection to a directory. Here lets see how doing this with .htaccess. It is the built-in feature in Apache using htaccess method. By doing this we could restrict access to certain users or search engines.
For creating an Apache password protected directories we will be needing a password file and the directory name which is to be password protected. We could perform this task by following a 3 step process.
- Configure Apache to use .htaccess file.
- Make a password file.
- Testing our configuration.
1. Configure Apache to use .htaccess file.
Add AllowOverride AuthConfig directive to http.conf file for these directives to work. So our http.conf looks like,
<Directory /var/www> Options Indexes Includes FollowSymLinks MultiViews AllowOverride AuthConfig Order allow,deny Allow from all </Directory>
Save and restart Apache server.
2. Make a password file.
Use htpasswd to create password for authentication when using Apache. For example, htpasswd -c password-file username
-c: attribute denotes create new file, will re-write if password file already exists.
username: second one username is used create user for password file.
Password file should be kept were it is not accessible by web.
To add new user using htpasswd, $> htpasswd -c /home/secure/<file> <username>
Make sure the file created is readable by Apache.
Now its time to create our htaccess file. Create an empty file .htaccess in our desired directory. Open the file for editing and add the commands below.
AuthType Basic AuthName "Restricted Access" AuthUserFile /home/secure/<file> Require user <username>
3. Testing our configuration.
Completing the step 2, we have almost finished. Now it is time to test the configuration, open the browser and try to access the directory were htaccess is added, eg:
http://localhost/project/<dir> or http://example.com/<dir>
If the above procedures are done correctly, the URL will be prompted to one login section requesting username and password.
Hope you have found this article useful, feel free to share your thoughts.
You may also look into other solved configurations related to htaccess over here.
Please fell free to share your thoughts and doubts regarding this here.