Protect your directory with .htaccess and .htpasswd


Have a demo / file that you want to prevent visitor without permission to see it? There are a lot ways to do it, one of it is protect it using apache .htaccess

First you need to create a empty .htaccess file, if you already have one in your root folder, just add the code in the same file. To know how to create a htaccess file, click here. I’ve mentioned it in one of my tutorial.

Copy the code below to your htaccess file:

AuthType Basic
AuthName "restricted area"
AuthUserFile /home/codinglover/public_html/.htpasswd
require valid-user

<Files ".htaccess">
order allow,deny
deny from all

Change AuthUserFile to where you put the htpasswd file. Please note that you’ll have to put full path to the folder.

AuthUserFile /home/codinglover/public_html/.htpasswd

I put it in the root folder together with .htaccess file.  

Save the file and put in your root of the folder.


Create username and password for the directory in .htpasswd

 You already have a file to tell the hosting to check for user access before showing the content to the visitor. Now you need to create .htpasswd and put the username and password inside.

The way of creating .htpasswd is the same with .htaccess. There are a lot htpasswd creator that can be easily found on google. Here’s one I found:

Enter the username and password you want and generate the code. You can have more than one set username and password in the file, just make sure 1 set per line. For example, this is how it should looks like in your htpasswd file:


Save the file and upload to the root of your folder and we’re done!


Things to take note

I’ve clicked cancel, why am I still able to see the content?

There are cases where the user save the username and password with the browser, in that case, even if they click “Cancel”, the content will still be display.


How do I logout from the “login” status?

Sadly, there’s no actual “logout” for this method. To logout

  • First, as mentioned, do not save username and password in your browser
  • Close your browser, the next time when you access the URL again you’ll need to login again.

Leave a Reply

Your email address will not be published. Required fields are marked *