Howto: Securing a folder with apache’s built in htaccess options
Tuesday, May 24th, 2011If your web site is running on Apache, and almost all are, there’s a simple way to protect directories on your web server. This method can be very secure, when combined with HTTPS and some good practices on your part, but it can also be a simple way to limit access to just a few people who know a password – perhaps as an alternative to Facebook sharing.
The feature being used is Apache’s HTTP Basic Authentication module. Apache has their own How-To at their web site, but here are the basics:
You need to add two files to your web server, and it helps if you have access to a terminal/command prompt.
Here are two key files and their their contents.
.htaccess
#Force HTTPS
#RewriteEngine On
#RewriteCond %{HTTPS} !=on
#RewriteRule ^(.*) %{HTTP_HOST}%{REQUEST_URI} [R,L]
AuthType Basic
AuthName "Restricted Files"
AuthBasicProvider file
# Needs full unix file address, output of pwd command
AuthUserFile /var/www/html/examples/guest_w_pass/.htpasswd
Require valid-user
These are basic .htaccess directives, that most web servers should allow. The first segment is to force the use of HTTPS, you might want uncomment that if HTTPS is important to your application. The second section turns on basic authentication and directs the web server to where to get the password file – you can put the password file anywhere your web server can access it and it does not have to be in the same folder as the .htaccess file. You are responsible for finding the full unix path to the file, either from the pwd command or the “Get Info” option inside a file browser.
.htpasswd
guest:{SHA}K8+J8fKKKxjnREM2J4/C72Qawa4=
This file is the results of the command htpasswd -sc .htpasswd guest. The s after the – is for SHA-based password hashing and the c after the – is for create. The file can be added to or updated with the command htpasswd .htpasswd username. Run the command htpasswd --help for more information.





