Apache2 - create password protected directory

My friend requested article about password protected access to public directories using .htpasswd file. Configuration of this is quite simple.

All you have to do is make sure that you have .htaccess and AuthConfig override enabled (on Ubuntu this is default AFAIK) files support enabled (somewhere in your /etc/apache2/apache.conf should be AllowOverride AuthConfig directive).

Make sure you have mod_auth enabled

sudo a2enmod auth_basic authn_file

Creating files

For making password protected directories you should create two files

  • .htaccess - file which changes configuration of Apache for current directory and subdirectories

  • .htpasswd - file created by utility htpasswd - there are stored user names and passwords

The .htaccess file

## make sure nobody gets the htaccess files
<Files ~ "^[\._]ht">
   Order allow,deny
   Deny from all
   Satisfy All

Order deny,allow
Deny from all
AuthName "Please enter password"
AuthType Basic
AuthBasicProvider file

# Full path to .htpasswd file
AuthUserFile "/home/johny/public_html/pass/.htpasswd"
Require valid-user

# Uncomment lines below if you don't want to
# enter password from some hosts
# (list of hosts is space separated)
#Allow from
#Satisfy Any

The .htpasswd file

  • Creating file with user - htpasswd -c .htpasswd johny

  • Adding new user to file - htpasswd .htpasswd johny

  • Removing user - htpasswd -D .htpasswd johny

Where .htpasswd is file name, and johny is username.


Make sure the file is NOT world writable - change it’s permissions (chmod 644 .htpasswd .htaccess).

What should I remember?

Suppose we have directory structure like this, what will happen:

./nopass      <= not protected
./nopass/passtest  <= protected (here is .htaccess file)
./nopass/passtest/also_protected  <= this is also protected because it's "below" .htpasswd

Additional references:


comments powered by Disqus