htaccess and htpasswd Tutorial

What are they?

.htaccess and .htpasswd are both files used to control access to your files and folders on an Apache server.  They are easy to configure and are a great way to add extra security to your website.

.htaccess can be used to redirect users automatically, request passwords, block access on specific directories or files, create custom error pages, change your file extensions, ban users by IP, limit access according to IP, stop people from seeing your directory contents (aka directory listings), change which file is the default file (such as index.html or index.php), and much more.

How do I create and save the .htaccess file?

You can easily create the .htaccess file using something like Notepad.  Just simply create a new text document and enter the neccessary information in it and that's it.

However, you may encounter problems when it comes to saving the file.  Windows isn't particularly fond of it's name, or the lack there of, so here's a few ways to work around that.

In Windows, you should be able to save the file as ".htaccess" (including the quotes) and it should work just fine.  If for some reason it doesn't work, save the file as something like htaccess.txt and then upload it to your server.  Then using your FTP client, change the filename to .htaccess and you should be done.

How To Dermine Path For .htaccess File

In some cases, such as defining where the htpasswd file is, you have to have the actual file path to the file and NOT the domain path.  On a local server, this is simple, but on a paid hosting server, this info can be rather difficult to find.  I've written a very basic PHP script that will tell you the path to where ever you put the file and open it at, such as the same folder as your htpasswd file is in.

You can download it from my downloads section or by clicking:

File Path Finder Script

How To Create Custom Error Pages

Perhaps you want to have custom error pages for your website because either your host uses some fancy pages promoting their hosting or there's nothing at all there.  Apache has a feature to do this, but if you're hosting multiple websites on your Apache server, you may want custom error pages based on that particular web site's design.  So here's how we can do that.

Add the following line to your .htaccess file:

ErrorDocument errornumber /file.html

Change the errornumber to the error number you're wishing to define, such as 404, 500, etc.  Then change /file.html to represent the path to your custom error page.  Here's an example, assuming my error file is in the same directory as the .htaccess file:

ErrorDocument 404 /404errorpage.html

You can define the directory using a directory path if necessary.  For instance, you may keep your error pages in a directory lower than your website's root folder, so you will need to define the path like so:

ErrorDocument 404 C:/errorpages/custom404.html

Here's a list of some of the most common errors:

401 - Authrization Required
400 - Bad Request
403 - Forbidden
500 - Internal Server Error
404 - Wrong Page or Missing Page (Broken Link)

How to stop directory contents from being viewed.

You probably don't want visitors to be able to view the contents of your website and surf around in your source files, because this poses a security risk.  One way to stop this is put blank or redirect index files in your folders, but you may also use the .htaccess file to solve the problem as well.

Create a new .htaccess file or add the following line to an existing one:

Options -Indexes

That's it!

Control access to a directory by IP

This is one way to allow specific IP's access to a directory or webpage according to their IP and blocking troublesome users from accessing it.  The problem with this will be if you or the blocked user has a Dynamic IP address.  If your remote IP changes for some reason, then you or the person you are allowing access by IP will be blocked out.  If the troublesome person changes their IP or uses a proxy, then they can bypass this ban easily.

The most pratical use I can think of for this is if you want to lock access to the local machine only, such as 127.0.0.1.  This way no other computer besides the host computer can access it.  This is assuming you have access to the computer, which is a safe assumption since this website IS about owning and running your own web server.

To block an IP, you would add this to your .htaccess file:

deny from 123.456.78.910

If you want to ban by the subnet, or the first few sets of numbers, you can do so by using something like this:

deny from 123.456
or
deny from 123

Beware of using this, because you may easily block several people who you actually want to have access that have the same subnet.

To block everyone from accessing the folders (including yourself via a web browser), then add this:

deny from all

Do note that these will still allow your scripts to run fine unless it takes you to a page contained in that directory, and then you will run into a problem.

I also want to note you can use this to block access to an individual file as well, such as a login page or something.  Here's the code for how to do that:

<files login.php>
order allow,deny
deny from all
</files>

You can also deny by file type as well.  Here's an example of that:

<FilesMatch "\.(htaccess|htpasswd|ini|phps|fla|psd|log|sh)$">
Order Allow,Deny
Deny from all
</FilesMatch>

The Deny from all line can be changed as indicated in the above examples.

There's several more things you can do and since this is an article and not a book, I'll link you to some useful links to learn more about it at the end of this article.

How to password protect directories and files

This is where the .htpasswd file comes into the picture.  It works along side of the .htaccess file and contains the usernames and passwords allowing access to a particular area or file, making access permissions more dynamic and flexible than just using the .htaccess file alone.

You'll probably find this far more useful, especially if you're trying to protect a login page that you may access from multiple locations or have multiple users accessing.  You can define multiple users and passwords in the .htpasswd file and the passwords can be encrypted as well for extra protection.

So let's begin with the first part, the .htaccess part of this subject.

The .htaccess File

The first part of adding password access is creating the .htaccess file.  With the following lines, everything in the folder you put the .htaccess file in and in the subfolders will be protected with this password:

AuthName "Section Name"
AuthType Basic
AuthUserFile /full/path/to/.htpasswd
Require valid-user

You need to change the Section Name to whatever you wish to define that section as, such as "Members Area", "Secure Area", etc.  Then you need to change the AuthUserFile /full/path/to/.htpasswd to reflect the correct path for your .htpasswd file. I recommend putting this in a folder below your website's root folder or in a seperate sub directory.

Protect A Single File With .htaccess

You may want to protect a single file using the .htaccess and .htpassword files and allow users to access the other files in the directory un-restricted.  I primary example of this would be if a login page is located in the same directory as other files such as index.php, etc.  Here's they way to do that:

<FilesMatch "login.php">
AuthName "Authorized User Only"
AuthType Basic
AuthUserFile /html/username/.htpasswd
require valid-user
</FilesMatch>

This will only require a password when someone tries accessing the login.php file and not any of the others in the directory.  This .htaccess file may be placed in a parent directory as well.

The .htpasswd File

This is the container file and the one that the .htaccess file will check for the correct password.  The truth is, this file can be named to whatever you like, just make sure you define it correctly in the .htaccess file.  This can be useful to set different usernames and passwords for multiple websites, but as a good rule of thumb and for the sake of keeping things simple, we'll just use the standard for now.

As mentioned above, I highly recommend putting this below your website's root folder or anywhere BUT the root folder if you do not have access to lower folders.  This is so that this file cannot be accessed and is a good safety measure.

Creating Usernames and Passwords

To create usernames and passwords, define them like this:

username:password

Seperate new usernames and passwords by putting them on new lines.
You can use encrypted passwords for extra protection by using a password generator script.  I will be adding one of these soon to this article, but I highly recommend the KxS Inc. one.
Once you have finished adding the usernames and passwords, simply save your .htpasswd file the same way you did the .htaccess and you should be done.

How To Access The Protected Files And Directories

Now that you've done such a great job a protecting them, you'll need to access them.  When you go to a directory or file in your browser that is protected by the .htaccess file, you will be prompted for the login info.  If you wish to bypass the login screen, you can go to the directory using this address to bypass the login screen:

http://username: This e-mail address is being protected from spambots. You need JavaScript enabled to view it /directory/

This will bypass the login prompt.  There are also some scripts to do this for you as well if you want to search for them.

 

CONCLUSION

The .htaccess file is an amazingly useful tool for webmasters.  It's dynamic and ease of use can make it a real time saver and greatly improve the security on your website.  There's several more things you can do with it as well and here's a few links to get you started digging deeper.

Links

KxS Password Encrypter

Apache .htaccess Documentation

Perishable Press - Stupid htaccess Tricks

Web-based .htpasswd File and Site Access Manager - (I haven't tried this yet, but it's free and looked promising.)



Comments
Add New Search RSS
Leave feedback
Name:
Your email:
 
Website:
Message Title:
Formatting:
[b] [i] [u] [url] [quote] [code] [img] 
 
:angry::0:confused::cheer:B):evil::silly::dry::lol::kiss::D:pinch:
:(:shock::X:side::):P:unsure::woohoo::huh::whistle:;):s
:!::?::idea::arrow:
Enter the text as you see it in the image.

!joomlacomment 4.0 Copyright (C) 2009 Compojoom.com . All rights reserved."

Last Updated (Wednesday, 02 September 2009 21:57)

 

!!REMEMBER: Support Forums!!

I still keep getting requests for support in the comments of posts and unfortunately I cannot give adequate responses due to the fact there's limited space and it just isn't the right place for support.
I therefore am encouraging visitors to PLEASE go to http://forum.myownserver.info for any support related questions. You will NOT receive any spam or anything you don't specifically subscribe to! I'm very meticulous about this myself and if at any time you need help stopping notifications from posts you previously subscribed to, contact me and I will promptly fix the issue.

Thank you for your participation in this!

Open SourceApache HTTP Server ProjectMySQLPHP
Twitter Feed
Make a Donation
This site does not run ads nor does anyone fund it. The owner and author is unemployed and pays for it himself, so if you're feeling generous, please make a donation of any amount to help out. Thank you very much.

Powered by easy paypal donation

Survey
Which is better?
 
Search
User Login



Visitors


Countries

30.3%United States United States
8.5%United Kingdom United Kingdom
7.7%India India
4.7%Australia Australia
4.5%Canada Canada

Visitors

Today: 35
Yesterday: 134
Last Week: 1143
This Month: 761
Last Month: 5006
Total: 52595


JoomlaWatch Stats 1.2.9 by Matej Koval