Howto: Securing a folder with apache’s built in htaccess options
Tue May 24 22:43:36 2011 EDT (-0400 GMT)If 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 ^(.*) https://%{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.
The password file can be generated anywhere. You can make the file through Terminal application on your own Mac or from a trusted web site like www.htaccesstools.com/htpasswd-generator/. Once you have file created you can uploaded it to the web server – if you have terminal access to your server you can of course do everything there. Only web servers configured in the worst possible way will ever disclose to the rest of the web a file or folder prepended with a . — like .htpasswd — but you may want to double-check.
And that should do it. Hopefully this will be a simple and time-tested way to limit access to content on your web server.