Protecting website and web folders with HTTP authentication (.htaccess & .htpasswd)
There's a quick and easy way to protect your website from being publicly accessed. You can also protect specific sub-folders and file types.
Bear in mind that this authentication method doesn't offer the highest security level but is usually enough for low to medium protection. You may want to use a proper login system using a database and SSL connection for added security, but that's not the topic of this post.
First, we need to create a .htaccess file in the folder to protect (or the root of the website to protect the whole site). This should be formatted as follow:
AuthType Basic AuthName "My Protected Area" AuthUserFile /path/to/site/.htpasswd Require valid-user
Then create a .htpasswd file (in the location you have specified in the .htaccess file). You will then need to generate a password hash to add to the file.
Here's a list of website which do the job for you:
Copy and paste the generate code into your .htpasswd file:
This is an example for username=username, password=demo
Make sure the full path to the .htpasswd file inside your .htaccess file is right, or you may have 500 error showing up.
Here's a PHP function that help you locate the full path of your .htpasswd file:
<?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>"; ?>
You can now browse to your protected area and a login form should appear!
Feel free to comment if you get stuck in setting this up.