Create secure password protected web pages and files through htaccess

By | April 2, 2019

Hello friends, Today we will learn to create secure password protected web pages and files through .htaccess in easy steps.

Sometimes in our project we need to protect web pages and files from an unauthorized person. You will also have seen many websites where their some pages have password protected or by username and password.

So anybody who is accessing that particular page, will need to put up correct credentials to access that page. So here we will discuss how to implement that feature in our web files or directory.

As many of us who are working as a developer know about .htaccess file. htaccess is commonly known as a most powerful and secure method  used for password protection.

So let’s start the steps

In this tutorial, I will let you know how to use .htaccess to password protect your web pages in simple steps.

There are so many website that protect their some pages by asking you for a username and password. Without entering valid credentials, you can not see the web pages.

Htaccess is known as most secure method of password protection. Using .htaccess you can protect single webpage or entire directory.

You will need to create two files .htaccess and .htpasswd in the directory that you are going to password protect.

For this example, I create a blog directory in /var/www/html/.

Now run the following command to generate .htpasswd file with username and password.

htpasswd -c .htpasswd your-user-name

After generating .htpasswd, you can check it should contain code like

user:$apr1$c4Ol904J$SmqVIhw53PGDmaVWM9Vhx.

Now add the following lines into .htaccess file

AuthType Basic
AuthName "Password Protected Area"
AuthUserFile /var/www/html/blog/.htpasswd
Require valid-user

Please replace /var/www/html/blog/.htpasswd with your valid file path.

Now You have successfully created a password protected application/directory.

Now when you will run your application in the browser it will ask for username and password.

If your web server does not support htaccess then above steps will not work and you will need to enable htaccess support on your server.