Password protect a website on Apache

December 10, 2014

Reading time ~2 minutes

Apache has an easy way password protect a folder, including root, therefore protecting the whole site.

This is what gets displayed in the Browser:

Apache needs to be configured so that when it receives a request to a protected directory it displays a login form. On submission it checks the details match those in a file. The file contains a user name and encrypted password.


  • Quick
  • Fairly easy


  • The form can't be styled - it takes on the OS/Browser appearance
  • Requires root access to the server or .htaccess enabled for vhosts


  1. Configure Apache
  2. Create the password file

1. Configure Apache

It goes without saying module mod_authn_file needs to on in Apache for this to work but it should be by default.

There's a couple of ways to set-up Apache Authentication but both require step 1, configuring Apache. Add the following to Apache config or a .htaccess file at the location to be protected.

# Protect directory
<Directory /var/www/website/folder-to-secure>
    <IfModule mod_authn_file.c>
    AuthType Basic
    AuthName "Protected area"
    AuthUserFile /var/www/.htpasswd
    Require valid-user

Make sure the paths to the protected folder and the location of htpasswd.file are correct. It's best to keep the password file above siteroot and/or start the filename with dot (period) so it's a hidden system file.

2. Create the password file

Option 1

Although it's easy to generate the file that contains the password, there's an online service to do it, Htpasswd Generator.

Simply add the details, download the file a place in the location specified in step 1.

The command-line tool might not be available on Windows.

Option 2

If you use Mac (Unix) or Linux this file can be generated using htpasswd program.

$ htpasswd -cb /full/path/to/file/.htpasswd username password

Where username is the username… wait for it… password is password.

Alternatively be prompted for a password:

$ htpasswd -c /full/path/to/file/.htpasswd username


-b Use batch mode; i.e., get the password from the command line rather than prompting for it.

-c Creates a new file and stores a record in it for user username.

Full details on htpasswd

htpasswd Apache details.

Or consult the manual in Terminal/Shell

$ man htpasswd

htaccess to password protect a specific server

If you use several environments for site: local, development, staging, production - here's a great gist from Jason Siffring: 'htaccess to password protect a specific server'.

comments powered by Disqus