Want to prevent people from viewing the files in a particular web directory ?

Here are the steps that will enable you to secure a web directory (in this example, /var/www/html/admin directory or http://yourip/admin/).

Step # 1: Make sure Apache is configured to use .htaccess file

You need to have AllowOverride AuthConfig directive in /etc/apache2/httpd.conf file in order for these directives to have any effect. Look for DocumentRoot Directory entry. In this example, our DocumentRoot directory is set to /var/www. Therefore, my entry in httpd.conf looks like as follows:

<Directory /var/www>
Options Indexes Includes FollowSymLinks MultiViews
AllowOverride AuthConfig
Order allow,deny
Allow from all
</Directory>

Change the value from “AllowOverride None” to “AllowOverride AuthConfig” (or “AllowOverride All” if you want to change other, non-authorization related options).

Save the file and restart Apache :
> sudo service apache2 restart

Next Steps are to create .htccess and a .htpasswd files :

  • From an SSH command prompt run: htpasswd -c /etc/apache2/.htpasswd yourusername and specify the password you want (change the file location to suit). This will create a .htpasswd file like: yourusername:me7asnd1UpLYw (Dont put the htpasswd file inside your webroot for security reasons). -c option is to create a new
  • In the Create Options File input, enter the name of the .htaccess file you wish to create. e.g. /var/www/html/admin/.htaccess

Your .htaccess file options will look like this:


AuthType Basic
AuthName "Protected Area
Require valid-user
AuthUserFile /etc/apache2/.htpasswd

Protect your .htacess and .htpasswd. (Read this)

CHMOD your .htaccess file 644 which translates to rw-r-r

chmod your .htpasswd file 640 (rw-r–)

$ chmod 644 .htaccess
$ chmod 640 .htpasswd

So in /etc/apache2/sites-available in default websites edit with nano and add a virtual host ( Read this for details  ) :

/etc/apache2/sites-enabled/000-default.conf
<VirtualHost *:80>
    ServerAdmin webmaster@localhost
    DocumentRoot /var/www/html

    <Directory "/var/www/html">
        AuthType Basic
        AuthName "Restricted Content"
        AuthUserFile /etc/apache2/.htpasswd
        Require valid-user
    </Directory>
</VirtualHost>