I was working on a site recently that password protected a directory and I found it interesting. I decided to try it out on my home Ubuntu box.

The Setup

First we need to let Apache know about the directory we want to protect. Navigate to the Apache config file.

sudo nano /etc/apache2/sites-available/000-default.conf

Add the following to the end of the file. In my example I’ll be protecting the /var/www/html/protected directory.

<Directory /var/www/html/protected>
Options Indexes Includes FollowSymLinks MultiViews
AllowOverride All
Require all granted

Then we need to create the directory to password protect on our web server.  Use /var/www/html/protected as we identified above.

sudo mkdir /var/www/html/protected

Next we need to make a file that holds the username and password that we will be setting to protect the directory. In a live server setting, you need to ensure this file is not accessible from the outside world so using /var/www is a great location to save this file. I will be calling the file httpass. Notice in this example, sdatic is the username and httpass is the filename. You will be prompted to type a password twice.

sudo htpasswd -c /var/www/httpass sdatic

Next you will need to change the ownership of the folder so that Apache can access it.

sudo chown www-data:www-data /var/www/httpass

Now we need to setup the directly to use this information. We will do this with an .htaccess file. I’ll use Nano.

sudo nano /var/www/protected/.htaccess

Enter the following into the file.

AuthType Basic
AuthName "Restricted Access"
AuthUserFile /var/www/httpass
Require user sdatic

Let’s make sure this file is owned by Apache.

sudo chown www-data:www-data /var/www/protected/.htaccess

Restart Apache.

sudo service apache2 restart

Now if you navigate to your web server you will be prompted for a username and password. My LAN address is and the directory is /protected.


Since this is an internal network I don’t have a lot of need for this but you never know when it might come in handy for an internal or external hosting server. Let me know if you have any use for this or would like to see how to do this on another platform than Debian/Ubuntu.

Article Categories:
Coding · Featured

Web developer and former photographer by trade...gamer and all around tech enthusiast in his free time. Christoph started sdatic.com as a way to organize his ideas, research, notes and interests. He also found it enjoyable to connect and share with others who parallel his interests. Everything you see here is a resource that he found useful or interesting and he hopes that you will too.

Leave a Reply

Your email address will not be published. Required fields are marked *