If you want to restrict access to certain web page or directory or an entire sub-domain of your website, what will you do? You can either setup an authentication system to confirm username and password of users before allowing them to access the webpage/file on your website but that will require unnecessary efforts.
Why would you want to Restrict Access to Web Pages
There can be multiple reasons for it, some of them are:
-
If you have a private forum on your website where only a certain set of users are allowed.
-
Or, if you have a under-development section on your website and you want to restrict access to only the developers working on coding and testing of those web pages.
-
You can also protect paid content on your website allowing only your paid customers to access it.
In short there can be many use cases for restricting access to certain section of your website.
Using .htaccess File to set Password Protection
It is very easy to password protect a website using .htaccess file. before we list down the steps to be followed, one very important point to remember, We can have one .htaccess file for every directory of your website for example, if your website has 10 directories, each with a few files, then you can create 10 .htaccess files with different rules applicable for the directory in which the .htaccess file is present.
Follow the following steps to password protecting any directory on your web server, it can can be your public_html directory too, in which case the whole website gets password protected:
Create two files in the directory which you want to protect with names .htaccess and .htpasswd (starts with a dot, yes)
In the .htaccess file, keep the following line of code:
AuthType Basic
AuthName "Password Protected Area"
AuthUserFile /path/to/.htpasswd
Require valid-user
Update the /path/to/.htpasswd to your web server's path to the .htpasswd file.
Now we need to add the entry for username and password in our .htpasswd file. To do so, add the content in the following pattern in the file:
sampleuser:encryptpass
where, sampleuser is the username and encryptpass is the encrypted password and colon :
is the separator. Similarly we can add multiple username and password combinations in new lines.
To encrypt password for .htpasswd file, you can use the following tool: https://www.web2generators.com/apache-tools/htpasswd-generator
Here is the PHP script to do the same:
<?php
// Password to be encrypted for a .htpasswd file
$clearTextPassword = 'some password';
// Encrypt password
$password = crypt($clearTextPassword, base64_encode($clearTextPassword));
// Print encrypted password
echo $password;
?>
Hope this article helps you in password protecting your website or any directory of your website. If you face any problem or have any confusion, feel free to comment.
You may also like: