This post is not so much a tutorial as my own notes on restricting access with .htaccess files and apache. As has been the case with many of my previous tutorials, the basis is writing the steps down so I can refer to them later. Turns out making notes public on a blog is a good idea. In any event, this will outline restricting access to directories on a user-level with .htaccess.
Create the .htaccess file
To limit access to a directory we need to create a .htaccess file where we will outline the restrictions for the location. Any folder within your publicly accessible web page can have its own custom .htaccess file. note: some shared hosting companies do not allow custom .htaccess restrictions for individual sites. You may need to check with your host on this.
Within your .htaccess file you would include something along these lines:
# sample .htaccess file
AuthName "Private Website"
require user username (optional)
In the above sample config “Private Website” can be any message you want displayed to the user when trying to authenticate to that page. /path/to/.htpasswd is what we will work on next in generating usernames and hashed passwords for authentication. require user username can limit access to only those users listed.
Create the .htpasswd file
In the .htaccess file we’ve outlined a path/to/.htpasswd file which we need to also create. It is a good idea to keep this file in a non web-accessible location. For example, if your web root is /var/www/html/ you might put the .htpasswd file in /var/www/.htpasswd. This way it is not accessible publicly and limits the chances of someone being able to get a hold of and attempt to break your hashed passwords for access.
To populate the .htpasswd file we’ll use the command htpasswd. To initially create the file we’d use:
htpasswd -cm /var/www/.htpasswd user-one
The -c will initially create the file. The -m will md5 encrypt the passwords for additional security. The htpasswd command will prompt you for a password.
To add additional users to your .htpasswd access list use:
htpasswd -m /var/www/.htpasswd user-two
Be careful not to use the -c option when adding additional users as this will recreate the file and overwrite previous entries.
Once these two files are in place access to the folder containing the .htaccess file will be limited to only those users listed within the .htpasswd file and require authentication via a password. This is great for sharing web accessible files with only certain users, creating private folders, etc.
If your host allows custom .htaccess file creation but does not provide you access to the htpasswd command you can try to generate your .htpasswd file using an apache installation on a local machine and copying the resulting files over.