Howto password protect a folder on your website

Hi,

although there are a quazilion how-to’s on the internet about this topic, I’ll add another to it:
How to safeguard a folder on your website with a username/password.

I make use of NethServer 7, but I guess on other versions it works quite the same.

Prerequisites: you have successfully installed and configured a website on the main server of NS, you have shell-access with root-privileges, and know how to operate VI.

OK let’s get started.
Assume you want to have a file index.html in folder ‘secret’, that only user John can access with his password.
First create the folder:

mkdir /var/www/html/secret

and create or copy index.html into it:

cp /some/location/index.html /var/www/html/secret/index.html

Now create a file .htaccess (yes, the dot needs to be there) in folder ‘secret’ with this content:

AuthType Basic
AuthName “Restricted Access”
AuthUserFile /etc/httpd/apasswd
Require user John

Location and name of the AuthUserFile can be chosen at your will, as long as apache can read it.
I’ve chosen to put it in /etc/httpd because all configfiles of the website are there.

Now go to /etc/httpd and as root issue the command:

htpasswd -c apasswd John

You’ll be prompted for a password, and asked to re-enter it for verification.
Now a file apasswd is created in /etc/httpd/ with a content like

John a6e7dcb80sh/H7T4Vva3qIblablabla

Last step is to tell apache to take note from this restrictions.
The following section can be placed in any of the already existing .conf files that apply to the public webserver.
However, for being simple to (re)find, I opted to make a seperate file:

cd /etc/httpd/conf.d/
vi htaccess.conf

add content:

<Directory “/var/www/html/secret”>
AuthType Basic
AuthName “Restricted Content”
AuthUserFile /etc/httpd/apasswd
Require valid-user

Of course to let this work, you have to restart the webserver:

service httpd restart

Now go to https://yoursite.tld/secret
You’ll be prompted for username and password before index.html is showed.

(^^^^ that’s in Dutch, sorry for that)

As said, a load of websites explain this stuff, and googling around learns more about adding more users, more folders etc. But htis will get you started.
Feel free to comment, I’ll try to update this topic when needed.

3 Likes

would you mind to add your howto to the wiki, I already started to write some notes on how to authenticate in apache (ldap, pwauth, pam)

http://wiki.nethserver.org/doku.php?id=developer:authentication_through_apache

Didn’t notice that so far, I’m sorry!
Hope that @johnjervig @ibico @bwdjames @Greg @jackyes will help you to test it!

The information is very useful as I am having my data in the site which I want to protect for security purposes.

Its really knowledgeable discussion thanks for sharing with us