Password Protect Your Web Directory via htaccess
We are often in a situation where we need to protect our site from general public. This might be when we are developing some proprietary app, or we are staging some development environment, and you don’t want those creepy web crawlers to index our site, which can obviously harm your ranking with duplicate content on live and dev servers.
There are many solutions to achieve that. You could do PHP authentication in each of the header file for authorisation.
To cater web crawlers, you could add a robots.txt file on your root directory with the following content:
However, for a quick and easy fix, that does not involve tempering with the core php files, we could use builtin functionality of htaccess.
Fire up your favourite ftp manager
Create a new file with name
.htpasswd in the directory that you want to secure.
Insert username:md5_of_pwd in the file. You can add multiple users in the file with different passwords.
You can generate the md5 hash of your password using this service: MD5 Generator
For example: for username: waqas and password: test, I will add the following code
Now create an
.htaccess file in the same directory that you want to secure and add the following code:
AuthName "Secure Document"
require user waqas
You need to add absolute path to your secure folder. If you don’t know the path, you can add a temporary php file with the following code to get the path
</php echo $_SERVER["DOCUMENT_ROOT];?>
Secure Document is the name that will be displayed when prompted for password. You can change to anything you like.
waqas this is the user that you created in other file. Make sure it matches.
In case of multiple users, repeat this line for all users:
require user abc
require user xyz
That is all. Now unauthenticated users will get a password prompt, when they try to visit your link
A side note: This method does not prevent bruteforce attack. Make sure your passwords are long enough, and use additional security features, like ip blocker, and/or creating logs like
ErrorDocument 401 /path/to/log.php
So be vigilant and be proactive.
If you like this post, please don’t forget to share. 🙂