.htaccess Basic Authenticaton

To restrict access to everything in a directory and everything below it, set up an .htaccess file and a corresponding password file.

Generating the .htpass file

Method 1

// create a file and a user
htpasswd -bc /somepath/outside/of/root/.htpass user1 password1

The -c directive creates a file .htpass in the directory somepath/outside/of/root/ containing a username user1. Be careful as this will overwrite an existing file of the same name. The -b directive means you must supply the password password1 at the command line when running the command – not recommended.

Method 2

When run, the command will prompt you to enter the password, which will be obscured – recommended.

// create a file and a user, password entered after prompt
htpasswd -c /somepath/outside/of/root/.htpass user1

Method 3

To add or edit a user/pass to an existing .htpass file, leave -b and -c out. You’ll be prompted for the new password.

// create/update a user/password, password entered after prompt
htpasswd /somepath/outside/of/root/.htpass user1

Password protecting a directory

Create a filed named .htaccess in the directory you want to protect, and drop in the below snippet.

AuthUserFile /somepath/outside/of/root/.htpass
AuthGroupFile /dev/null
AuthName "Private Page"
AuthType Basic
require valid-user
Snippets and tagged