If you are looking for a way to password protect a folder or file on your website, maybe for demo sites or building a new website as work is in progress then you can use a .htaccess file to control the access availability. This is obviously if the server allows this, most web servers will.
Password Protecting Web Pages using .htaccess
This works by blocking access unless a username and password is provided.
The first thing to do is create a password file and call it “.htpasswd” and in this file we will put an encrypted password with a username like this:-
You need to change the “testuser” with the name you require. The password shown here is “password” encrypted to “80KN95Q9e5YXc”.
You can add more users simply by adding a new line for example:-
.htaccess Password Generator
Now we need to create the security request in the .htaccess file. This is done using the following code:-
AuthUserFile /path/to/the/password/file/.htpasswd AuthType Basic AuthName "Protected Page" <Files "index.php"> Require valid-user </Files>
Change the filename to specific file you are looking to protect, in this example it would protect the homepage of any website using index.php such as WordPress.
You can add more files by simply adding:-
<Files "anotherpage.php"> Require valid-user </Files>
You need to also change the path the password file. If you do not do this you might not be able to access the website or get an error.
To identify the full path for the password file location simply create a file called “findfullpath.php” and then copy and paste this code into it:-
<?php $dir = dirname(__FILE__); echo "<p>Full path to this dir: " . $dir . "</p>"; echo "<p>Full path to a .htpasswd file in this dir: " . $dir . "/.htpasswd" . "</p>"; ?>
Now upload into the directory where you are storing the password.
Go to the “http://www.domainname.co.uk/?????/findfullpath.php”
Obviously replace the ???? with the folder name where you are storing the password.
.htaccess Password Protection Process
- 1. Create “.htpasswd” with username and password.
- 2. Upload to hosting
- 3. Identify the full path to the “.htpasswd” file.
- 4. Edit or create the .htaccess file
- 5. Add the related security code specifying the full path to the “.htpasswd” file and the protected files.
You will need something like notepad to generate the files required and if your operating system is not letting you work with “.” then simply create the files “htaccess.txt” then upload via FTP and rename.
Testing .htaccess Folder Protection
Go to the specified area of the website you are looking to protect and you should get a pop up with username and password.
If you are looking for an MD5 Hash Password Generator then click here.