How to password protect a page on your website

02 Nov 2020

Here is a tutorial on how to password protect a page on your website. The page, files, and sub-folders of the page will will be inaccessible without the password.

You will need:

Let’s get started!

On your web server via ssh navigate to a private part of the server. In my case I have a private_files folder in the root of my webserver which is not public to the internet and is specially set up as the advised location for these types of files by my host provider. In that location we’re going to create a password file (replace the username to your prefered username).

htpasswd -c  .htpasswd username

It will prompt you to enter a password and then to confirm it. The reason for doing this on your server and not locally is that Apache will automatically use the encyption to make the password file that it will later use (when your password protected page is working as it should be) when it cross references the the plain text password entered into the authorisation box with the password file.

Once created the file is hidden on most systems as it starts with a “.”. Check that it’s there by opening it in your text editor. For me this looks like:

nano .htpasswd

You should see something that looks like (just an example!):

username:$blah$lwihjqhi81i4u187u91hhjafjhsdfh/1hksh

You can see that the encryption has worked. The encrypted password is nothing like the password you entered in plain text.

Ok, now we’re going to create the .htaccess file. Just before we do, lets return the path to the current folder we’re in where we created the password file. We’re going to need it in a sec. Type:

pwd

To create the .htaccess file open up your text editor (I preferred to do this one locally). Add this:

AuthType Basic
AuthName "My Restricted Website"
AuthBasicProvider file
AuthUserFile /full_path_to_your_password_file/.htpasswd
require valid-user

Remembering to change the path to the .htpasswd file to what you returned with “pwd”, and also give the auth box a name you prefer.

Right, now the rest is easy. Just copy the .htaccess file to the folder you want to protect on your website.

When you navigate to the password protected part of your site you’ll be confronted with a login box. Enter the username and password (plain text version). Congratulations! You’re done!

/James