How to Password Protect a Directory on Your Website running on Linux? Only allow certain users or members to access portions of your site

Requirements

1. website must be running on an Apache web server.

2.  Your web host must have enabled .htaccess processing — that is, they allow you to customize your web server environment using localized configuration files called .htaccess files.

3. You must have Secure Shell (SSH) access.

Steps to Protecting a Directory with a Password Using .htaccess on Apache

1.Login to server using SSH

2. Add the following lines to the start of your .htaccess file

        AuthName “<Your website name> Members Area”
        AuthType Basic
        AuthUserFile /path/to/your/directory/.htpasswd
        require valid-user

Please note that you will have to modify the above according to your situation. Lets understand what all are those attributes

i. AuthName
Change “Members Area” to any name that you like. This name will be displayed when the browser prompts for a password.

ii. AuthType
You do not have to modify this line.

iii. AuthUserFile
You will later create a file containing passwords named .htpasswd. The “AuthUserFile” line tells the Apache web server where it can locate this password file. Full path to the file is to be used here

iv. require
The line “require valid-user” means that any user specified in your .htpasswd (ie, password) file will be able to access that directory.

4. Create .htpasswd file using the below given command

htpasswd -c .htpasswd your-user-name

It will prompt you for password and confirm password. Enter those, a file called .htaccess would be created. And you can review the content of the file using the command

cat .htpasswd

5. Restart apache server

service httpd restart (for centos/fedora/redhat)

service apache2 restart (for Ubuntu)

6. Now access your website on browser, it will prompt you for username and password.

Now you have completed the setup. enjoy!