The blog

Simple Password Protection for your website page

Quite often you’ll need to password protect a web page. This can easily become difficult if you need to authenticate users that belong to groups or roles. But for just a quick password protected page, you can use .htaccess and Apache’s authentication.

You’ll need ssh or ftp access, and your server must be configured to allow .htaccess overrides.

To setup the authentication, you’ll have to do only a few things:

  • Create a users file and assign usernames/passwords
  • Tell .htaccess to use authentication

Create a users file using htpasswd

First login to your server and navigate to just above the web root folder. For example, say our web root was webroot in our virtual host’s folder. We would want to create a directory that’s just outside of the web root folder. Below I created the directory passwd, which we’ll use to keep our users/password file.

+ example.com/
+ webroot
  - .htaccess
  - index.html
  - about.html
+ passwd

So, let’s cd into that directory:

ssh me@example.com
cd passwd/
htpasswd -c users steve
New password: *****
Re-type new password: *****
Adding password for steve

The htpasswd command will create the username and associate an encypted password with the user, in my case, that user is steve. The -c tells htpasswd to create the file.

To add another user, don’t use -c. You can use htpasswd again like so:

pwd
example.com/passwd
htpasswd users tom
New password: *****
Re-type new password: *****
Adding password for tom

Now we have two users (steve & tom) and passwords for each stored in the file example.com/passwd/users. Next, we have to tell apache to use authentication with that users file.

Tell .htaccess to use authentication

First login to your server and find the .htaccess file. If it doesn’t exist, you can create one directly under the webroot. Make sure your ftp client is set to display hidden files, or you won’t see that the file was made. Also, you’ll need to make sure your server is configured to allow .htaccess overrides.

pwd
example.com/webroot
nano .htaccess

That last command will open up the nano text editor. You may prefer to use other editors, such as vi or pico. After opening the file, you just need to add a few lines and you’ll be good to go.

AuthType Basic
AuthName "My Protected Area"

this needs to be the full server path

often it's similar to /var/www/vhosts/example.com

AuthUserFile "/var/www/vhosts/example.com/passwd/users" <LIMIT GET> require valid-user </LIMIT>

Now save the .htaccess file and visit example.com in your browser. It should require your login before displaying any content.

If you have trouble, try going through the steps again. If you still can’t get it to work, check that your host allows .htaccess overrides.

Leave a Reply