Beginners Guide to .htaccess File with Examples

htaccess file allow us to make configuration changes on a per-directory basis. htaccess file works in Apache Web Server on both Linux/Unix and Windows operating system. This article has some basic .htaccess examples, such as htaccess redirect, to get you started with .htaccess right away. Just copy and paste the lines mentioned in this post below, with or without any modification, in your .htaccess file and it should work.

There are several things that developers, site owners and webmasters can do by using .htaccess file. Let’s look at some of them:

  • Prevent directory browsing
  • Redirect visitors from one page or directory to another
  • Password protection for directories
  • Change the default index page of a directory
  • Prevent hot-linking of images from your website

Since .htaccess file allows us to make changes on a per-directory basis, the following are valid places to put the .htaccess file in:

/.htaccess [placing in root folder of the site]
/content/.htaccess [placing in content folder]
/content/html/images/.htaccess [in the images folder]

:idea: Any command that you place in .htaccess file will affect it’s current directory where it is placed and also it’s sub-directories. You may put a .htaccess file in the root folder such that it will affect the whole site.

:idea: Make a backup of your .htaccess file [if you have any] before you attempt any of the settings mentioned in this article. I must not be held responsible for any consequences that arises due to editing your .htaccess file. ;)

Working with .htaccess files

For creating and editing purpose, a normal text editor such as notepad will do. Alternatively, you can download a free copy of PSPad for easy editing. To be able to see files in your FTP software, you must enable settings in your FTP client to see hidden files on the remote server [applicable to your system as well]. When done editing, you can save the file with double quotes in windows. [Save file as ".htaccess", with double quotes]. This will save the file as .htaccess and will not prompt you for a file name as such. Let’s now move on to some common .htaccess file example.

Allow/Deny Directory Browsing

When directory browsing is on, people accessing a URL from your site with no index page or no pages at all, will see a list of files and folders. To prevent such directory access, just place the following line in your .htaccess file.

IndexIgnore */*

Many hosting companies, by default deny directory browsing and having said that, just in case you need to enable directory browsing, place the following line in your .htaccess file.

Options +Indexes

Redirect visitors from one page or directory to another

It’s quite simple. Look at the example lines below and place similar lines in your .htaccess file of the root folder and it will do the rest. [Remember to use permanent keyword in the line to tell the search engines that the old link has moved to the new link]. You can also setup multiple redirects using htaccess.

Syntax: Redirect permanent [old directory/file name][space][new directory/file name]

Redirect permanent /olddirectory /newdirectory
Redirect permanent /olddirectory /somedirectory/newdirectory
Redirect permanent /oldhtmlfile.htm /newhtmlfile.htm
Redirect permanent /oldhtmlfile.htm http://your-domain.com/newhtmlfile.htm

All the above lines are valid. Just remember to replace the file/directory names with actual ones.

Change the default index page of a directory or site

Almost every hosting company will have index.htm, index.html, index.php, index.asp, default.asp, default.html as the default index page names in their web server settings. So, in case your site or directory does not has a file name which matches a name from the list above, chances are that your visitors will either see a list of all the files and folders [through directory browsing] or will not see anything at all. To change the default index page’s name for a directory or the site, place the following line in the .htaccess file of the root folder or the particular directory for which you want to change the index page’s name.

DirectoryIndex homepage.htm
DirectoryIndex somepage.htm

To have more names, put a space between file names and it will take into considerations all those file names as possible index page names. Which means, if it finds a filename matching a list of names you supplied [in the given order] in .htaccess, then it will open that page as the index page for the directory. The below line, with multiple names, is also a valid usage:

DirectoryIndex homapage.html somepage.html myindexpage.html anything.html

:idea: Remember, each entry must be in one line only.

Preventing hot linking of images from your website

If your website contains images which people from other websites are linking to and you get charged for the extra bandwidth, then placing the following lines will prevent any such image hot linking. Most of the hosting companies provide this feature in their control panel itself, such as CPanel. This trick requires mod_rewrite engine to be on in Apache on your web server.

RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www\.)?your-domain.com/.*$ [NC]
RewriteRule .(gif|jpg)$ – [F]

In the above code, replace [your-domain] with your actual domain name [without www], and instead of (www.\), use your actual subdomain name (sub-domain.\)

Prevent access to your .htaccess file (.htaccess security)

This article would remain incomplete without mentioning this trick. ;) To prevent visitors from viewing your .htaccess file, place the following lines in your file. Of course, by default most Apache installations will not show .htaccess file but just in case.

<Files .htaccess>
order allow,deny
deny from all
</Files>

More information and detailed documentation, visit Apache website.

There’s also a second part to this tutorial – Beginners guide to .htaccess file with examples – Part II and you may also be interested in the Apache mod_rewrite examples for writing search engine friendly URLs.

Happy .htaccess[ing] ;)


Facebook
Twitter
Delicious
Stumble
Technorati
Subscribe to feed

70 Responses to “Beginners Guide to .htaccess File with Examples”

id just like to say that htaccess files are a weak form of security, they have some nice features, but you should never rely on them alone.

Gavin,
I agree with you that one should not rely on htaccess alone, but when it comes to security point of view, I have never seen an example of htaccess file getting hacked or exploited. For password protecting directories, I would not go with htaccess but use something else.

thank you. i was looking for httaccess tutorials. perfect timing.. :)

http://thygoodies.blogspot.com/

Nice to know that it was of some help to you. I am writing an advanced tutorial on htaccess already ;)

The DirectoryIndex should have no space in between Directory and Index.

Another good resource for your site to have would be the “Mod Rewrite Cheat Sheet”, Mod Rewrite is the part of the guide (for you beginners) that prevents the Hotlinking of images and such. One of the many various options that a .htaccess file can control.

Link: http://www.ilovejackdaniels.com/apache/mod_rewrite-cheat-sheet/

@Jak Wilkins

Thank you pointing it out. I have corrected it. I have included a task in my to-do list to write a tutorial on mod_rewrite as well. Should be up by this weekend.

@anon
Thank you for putting it up there!

Apache wont give you access to any file, which name starts with .ht, so the last step is unnecessary

I have a directory on my server for images i use on forums, smilies etc. In order to restrict others from using them on forums I’m not on i use the following :

RewriteEngine On
RewriteCond %{HTTP_REFERER} !^http://(www\.)?(DOMAINTOALLOW-1|DOMAINTOALLOW-2)(\.co\.uk|\.com|\.ac.uk|\.org)/ [NC]
RewriteCond %{HTTP_REFERER} !^$
RewriteRule .*\.(gif|jpg|jpeg|bmp|png|swf)$ http://YOURDOMAIN/images/hotlink.gif [R,NC]

http://YOURDOMAIN/images/hotlink.gif

I should point out to viewers that htaccess files generally get parsed every time a page is viewed, which means that if you have a lot of htaccess files in multiple directory levels, it could potentially lead to a great deal of performance loss. If you really want a lot of flexibility without performance loss, you should set all these flags inside the actual Apache configuration files if at all possible. Granted this is not feasible on a shared hosting server, but for any self-hosters, or for people who have access to this part of your server, it is highly preferred over the use of htaccess.

Cheers, and it’s a good introduction. Thank you.

Nice writeup. I also like this htaccess rule that saved my life a few times on poorly configured apache servers.

how can i edit and download my .htacces from my web hosting server via ftp? i know that this file hidden… help me out! ;)

@jsonvega

You will have use an option to show hidden files in your FTP client software. Depending on whichever FTP client software you are using, there must be an option somewhere to show hidden files. If your ftp software can execute commands, try ls -a [list hidden files] and make a backup before you do anything ;)

Nice work, but what’s really missing on the web is a guide to do all this stuff in lighttpd!

Great Article :-) . Thank you for sharing your knowledge with us.

Blessen
Sr.Executive , Bobcares

@Blessen

Thank you for your time to read it :)

i try all these things to secure my directory on windows server but all in vain…

plz help me and suggest the another way to protect my A directory or all…

thanks and regards

I assume you know how to create .htpasswd file. Put the below lines in your .htaccess file

AuthUserFile /.htpasswd
AuthType Basic
AuthName “Auth Required”

<limit GET POST>
require valid-user
</limit>

Great article man.. It’s simple and clear. It’s really good. keep up the good work and momentum

Eshwar – Thank you for the kind words of encouragement!

did you miss out a backslash?

should the following

RewriteCond %{HTTP_REFERER} !^http://(www.)?your-domain.com/.*$ [NC]

–>

RewriteCond %{HTTP_REFERER} !^http://(www\.)?your-domain.com/.*$ [NC]

Thanks for pointing that out. I am correcting that now!

The hot-linking tip is nice, but…it doesn’t work if one’s ISP disables mod_rewrite. :-(

On the other hand, the tip described here does: http://www.sonic.net/support/faq/web/htaccess.shtml#imagetheft

I would guess the performance impact is nearly the same, possibly slightly lower…but it’s been many years since I did much with Apache, so I don’t know for sure.

We have a membership site that was created in php and uses null.html then skip to main.php as the home page. username and password were created by our programmer. But, he has left and the site has some suthencation problems. Security is oue main priority. Can htaccess be used with a system that has an established username / password system? You comments are appreciated Thanks!

Jack, htaccess can be used to grant access on folder-by-folder basis. I would recommend you NOT to use htaccess for user management within the site but rather use it only to give access to folders in the site.

Example: yoursite.com/members/ — Here if someone opens that URL, you can use htaccess to grant access to files within that folder, but I think for your membership site, you may want some sessions and cookies management as well. You should consider mysql based user management for that. If you need help with security management in your site, do drop in an email to rajATbloghashDOTcom and I will try to help you best I can.

Cheers !

In search engine point of view is there any problem if there is only three key words in my keyword tag. will it effect on search engine ranking or SERP result.

Hi Raj

how my domain will take automatically www. in browser how .htaccess plays role to make it and will it make any difference if my site will open without www please let me know

Hi Inder,

#1. Using Metatags for keywords should not make any difference as such as most of the search engines give least importance to meta tags based keywords. But, since on Internet, Search Engines treat each page as a single entity, you might want to make sure that every page of yours has different keywords based on the respective content. An example would be if your site is about automobiles, and consists of two pages, one for Benz cars and second for Truck, then consider having keywords as “cars, benz” for first page on cars and “trcuks, heavy trucks” for the second page. That should be fine. However, if you are using keywords, I would recommend using more than just few keywords. Identify the keywords in your pages, number of times they are repeated and use them.

#2. Having your domain with or without www should not make any difference from search engine’s point of view. However, sometimes, you might see difference in number of pages indexed, backlinks etc when compared to with and without www. I use htaccess to detect an incoming request for non www request and return http://www.bloghash.com without appropriate header codes. See the second part of this article which has an example for redirecting a non www to http://www.domain.com … lemme know if this helps..

Cheers!

Hi Raj,

Where r u from what is your profile job details

Hey Inder,
I have sent you an email with information. – Raj

what is the importance of robots.txt file in a web page in search engine point of view
and why we will add it ?

robots.txt is a file commonly found on all web server and primarily used as an exclusion mechanism. Suppose, you don’t want certain directories to be included by search engines in their index, you can put those directories in robots.txt and search engines will not index them. This link (http://googleblog.blogspot.com/2007/02/about-copiepresse-decision.html) may be of your interest. And also this one -> http://www.bloghash.com/2006/11/robotstxt-exclusion-implementation-guide/

Thanks for the tutorial. I’ve had a couple of problems with hotlinkers. I’m going to try to apply your htaccess method to block them. I mean, if you want to use the content, at least upload it to your own server and stop using my precious expensive bandwidth! I have one question. You say that if I place the htaccess file in one directory, the rules will apply to all subdirectories and subdirectories of those directories below it. I actually have a large htaccess file. When Apache parses it, does it use a lot of processing power? Since my large htaccess file is in the public_html folder, will that slow down my server?

Thanks
Allan
hacker not cracker

Hi Allan,
I am glad you liked this article. Whenever a folder is called, could be a root folder, the htaccess file is picked up and processed every time. It certainly demands processing power and if your htaccess file is significantly larger, it will require greater processing time. A file of few kilobytes in size does not matter so much, but if your site receives lot of traffic, then in that case, instead of having a common htaccess file, it would be better to have specific htaccess file in the folder. Example: If you want to prevent image hot linking, instead of putting the file in root, have a htaccess file in the images folder only and for the purpose of preventing hot linking. [You can still have a htaccess in root if your site does not get thousands of requests a day]

The site looks great ! Thanks for all your help ( past, present and future !)

You’re Welcome :)

Trackbacks

  1. Robs Blog » Blog Archive » Beginners guide to .htaccess file with examples
  2. Beginners guide to .htaccess file with examples « Digged Stories
  3. studiomaqs » Reading: November 06
  4. Prime News Blog » Blog Archive » Beginners guide to .htaccess file with examples
  5. sickofmusic.com » .htaccess guide, Start workin that apachebitch out !
  6. I Only Wish » Blog Archive » Beginners guide to .htaccess file with examples
  7. Quick Links at Blog For Smart Masses
  8. HTACCESS files for Beginners « Linux and Unix Links of interest
  9. Mac Professionell » Blog Archive » Was man mit .htaccess-Dateien alles machen kann – für Anfänger erklärt
  10. pix.l|ne ’s Journal » Blog Archive » Beginners guide to .htaccess file
  11. ADRIFT » Daily Zeitgeitst
  12. its about time» Blog Archive » links for 2006-11-21
  13. links for 2006-11-22 « Where Is All This Leading To?
  14. TimmyBLOG » links for 2006-11-22
  15. Beginners Guid to .htaccess « Interknox Networks
  16. links for 2006-11-22 « kumara
  17. Notes » links for 2006-11-22
  18. links for 2006-11-22 · Lawsy.net
  19. Beginners Guide To .htaccess Files With Examples » Linux Knowledge for Sys Admin
  20. links for 2006-11-22 at MRPETERPETER
  21. Beginners guide to .htaccess file with examples at blog.jsonvega.net
  22. Interesting Links - November 22, 2006 « Freakitude Technology Blog
  23. links for 2006-11-22 at Amy Stephen
  24. Like Your Work » Blog Archive » links for 2006-11-23
  25. MalwareTeks Blog : Beginners guide to .htaccess file with examples
  26. colector inusual | plataforma de creatividad interactiva - desde 1997
  27. sysadmins.cc » Blog Archive » Beginners guide to .htaccess file with examples
  28. Beginners guide to .htaccess file with examples — XSet Archive
  29. prevent image hot-linking « me looking so small in this world
  30. Brent Meshier » Preventing image hotlinking with htaccess
  31. Basic htaccess « 0ddn1x: tricks with *nix

Categories

RSS feed