A .htaccess file is a way of protecting content on your webspace, controlling who has access to what and much more. The basics of using a .htaccess file for user-based access control are:
- Creating a master password file
- Creating the restricted directories
- Creating a .htaccess file
The password file
.htaccess files run off a users file somewhat similar to that of a unix system. If you want to start using .htaccess files, first you must create this file.
htpasswd -c /srv/webspace/$USER/files/.htpass username
where /srv/webspace/$USER/files/.htpass is wherever you decide to keep the file. I used .htpass because it keeps the file hidden when I'm working with my home directory. "username" in the command should be changed to whatever username you want to add first, $USER is your Netsoc username. To add another username, simply run
htpasswd /srv/webspace/$USER/files/.htpass otheruser
Each time you run htpasswd to add a user you will be asked for the password twice.
Now we need to set the users file up so it can be seen by the world. Thankfully, htpasswd uses DES to encrypt the passwords by default (MD5 and SHA encryption schemes are available). However, this is not completely secure. To make the file readable, run
chmod 755 /srv/webspace/$USER/files/.htpass
Now, we are ready to create a restricted directory.
The restricted directory
Start off making a directory like any other:
And now you set correct permissions for the folder - note that these permissions are not the standard 755 web permissions.
chmod 711 /srv/webspace/$USER/files/
There, that wasn't too bad, was it?
The .htaccess file
Now we create the .htaccess file. With your favourite editor (if you don't have one yet you're probably best off using nano) enter the following into the file:
AuthType Basic AuthName "OMG NO PLZ STAY AWAY FROM FILEZ" AuthGroupFile /dev/null AuthUserFile /srv/webspace/nosmo/.htpass
Now, make the .htaccess rules readable:
chmod 755 /srv/webspace/$USER/files/.htaccess
And you should be good to go.
More advanced tricks
Host/IP based access restriction
.htaccess files allow for many different kinds of access restriction. For example, if you wanted to deny access to all but visitors from within Trinity, the following rule might be of use:
order allow,deny deny from all allow from .tcd.ie allow from 134.226.
The "require valid-user" line above allows access to all users in the .htaccess users file. However, if you want to restrict access on a per-user basis, change the line to the following:
require user secretperson
Now the only valid username and password for the page is secretperson (if that is the only require user line in the .htaccess file).