IT & Programming

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

Your Goal:

You have a url for example or 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 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


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


If everything is set and if you open your url 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 *