How to Password Protect a Website or Web SubDirectory With .htaccess & .htpasswd

Working on a website that you need others to see, but not the whole world? Password protecting a website (or a sub directory within a website).

Protecting files on your website from unauthorized users can be very important. You can use PHP or any language to listen for login authorization information on each page, but that doesn’t protect your images, documents, and other media and it is not proper way to do so.

That’s why I’ve found the new method of protecting files and directories the most reliable and is actually a pretty easy thing to do.

screenshot_001_3

To password protect we will use .htaccess and .htpasswd method.

Step1: Basic Coniguration

To make .htaccess files work as expected, you need to have below line in your site Apache configuration,

AllowOverride All

So your file will look like

<VirtualHost *:80>

    ServerName password-protected.com
    DocumentRoot /var/www/PasswordProtected
    <Directory /var/www/PasswordProtected>
        # This relaxes Apache security settings.
        AllowOverride all
    </Directory>

</VirtualHost>

This tells Apache that it’s okay to allow .htaccess files to over-ride previous directives. You must reload Apache before this change will have an effect

sudo service apache2 reload

Step2: Create .htaccess and .htpasswd files

Create a file called .htaccess in the directory that you want to password-protect (in my case I am using /var/www/PasswordProtected directory) with the following content

AuthUserFile /var/www/PasswordProtected/.htpasswd
AuthName "Authorization Required"
AuthType Basic
require valid-user

Then create the file /var/www/PasswordProtected/.htpasswd which contains the users that are allowed to login and their passwords.

We do that with the htpasswd command, to use this command make sure apache2-utils package is install.

htpasswd -c /var/www/PasswordProtected/.htpasswd USER1

The -c flag is used only when you are creating a new file. After the first time, you will omit the -c flag, when you are adding new users to an already-existing password file. Otherwise you will overwrite the file!!

And that’s it you are done !! Your website is password protected now.

Hope you find this tutorial helpful. Feel free to ask questions! Don’t forget to like or to leave a comment if its really help you.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s