Password Protecting your website with .htaccess and .htpasswd

If you are running your own website sometimes you may find it necessary to password protect a portion of your website to have an extra layer of security. Maybe you have some downloads you do not want the general public to get to. Maybe you just have some pages you would like to keep fairly private. If you are using Linux and Apache this is can be done pretty easy using .htaccess and .htpasswd.

The first step in setting up your password protected directory is to create the .htpasswd file. To do SSH into your website. Navigate to a directory that is not viewable from a web browser that you have access to. Type in the command below where username is the user name you want.

htpasswd -c .htaccess username

It will ask you for the password and to confirm the password.

Now you will need to edit the .htaccess file. Navigate to the directory you want to protect and create a new text file called .htaccess. I usually use the program nano to do something small like this but use what ever you like.

In the .htaccess file put in something like below where user name is the same as the one you put into the .htpasswd

AuthUserFile /path/to/.htpasswd
AuthGroupFile /dev/null
AuthName “a quick name for the user/pass dialog”
AuthType Basic
require valid-user

Now navigate to the directory with your web browser and see if it works. If it does not you may have Overrides off. To enable them you will need to edit your apache config for your website. Your config file will usually be httpd.conf or if you are using a domain name you may have its own config (usually named or something close to that). If you are not sure contact your web server administrator to find out. Once you find the config for your website look for the line that says AllowOverride. If you plan on using .htaccess for a lot of things you can simply change it to All. If you only want to do passwords with it, changing it to AuthConfig should work fine as well. Once you make the changes and save. You may need root access to do this, if you don’t have this contact your web server administrator and as them to set AllowOverrides for your apache config.
You will need to restart the Apache services to continue. There are different ways of doing this below are commands that may do it for you pick the one you like best.

/etc/rc.d/rc.httpd restart
apachectl graceful
apachectl restart
service httpd restart (for fedora/redhat users)

Hopefully this quick tutorial helps you out.