IT & Programming

How to protect a URL with authentication using .htaccess and .htpasswd

Your Goal:

You have a url for example www.yourwebsite.com/controlpanel or www.yourwebsite.com/administration that you want to protect so that only some authorized people can access it. You want to protect this url from website visitors or search engine crawlers. 

This is possible with .htaccess and .htpasswd to protect a url which is either physical virtual.

Creating .htpasswd file:

First step is to create a file in your root directory or public directory and name it .htpasswd

Second step is to generate a username and password that you you need to put into your .htpasswd file. If you do not know how to generate username and password for .htpasswd file then go to www.web2generators.com where you can easily generate username and password for your .htpasswd file.

Once you generated your username and password string, put it in your .htpasswd file as shown below. In my case username was blog and password was test123

blog:$apr1$mzi0cxl6$wQwC5WZ4C37GZwXG.0b7g/

Creating or updating .htaccess file:

Add blow given code to your .htaccess and set path to your .htpasswd file (that your created earlier) for AuthUserFile variable. Replace /controlpanel with your own url that you want to protect.

SetEnvIf Request_URI ^/controlpanel require_auth=true
AuthUserFile /var/sites/yourwebsite/.htpasswd
AuthName "Protected"
AuthType Basic
Order Deny,Allow
Deny from all
Satisfy any
Require valid-user
Allow from env=!require_auth

Output

If everything is set and if you open your url www.yourwebsite.com/controlpanel then you should see a prompt to enter Username and Password for authentication.

Leave A comment

Email address is optional and will not be published. Only add email address if you want a reply from blog author.
Please fill required fields marked with *