Leverage your .htaccess file efficiently

Wednesday, March 16, 2011

Simple and useful guide about .htaccess file with examples...

The .htaccess file is a configuration file which is used on Apache based web servers to control many features of the server. The .htaccess file gives webmasters a lot of control over their website. The file contains the configuration statements (web server configurations) to customize the Apache Web server software for the website.

Hypertext Access, commonly shortened to .htaccess file is an incredibly useful feature which allows webmasters to control so many aspects of their website and how it works. The file acts as a local configuration file so that an individual website can customize the configuration to match its requirements. Other .htaccess files in subdirectories may change or nullify the effects of those in parent directories.

Leverage your .htaccess file efficiently

You can use any text editor to create or make changes to .htaccess files. Be sure .htaccess file is uploaded in ASCII mode, not BINARY, or it won't work. A web master should be very careful while editing the .htaccess files, as even a small mistake can make the website stop working. Web master should immediately test the site to be sure it works.

Below are the most useful .htaccess examples:

Redirect from Non-WWW to WWW version

There is potential for URL Confusion and splitting of Pagerank and Link Value by allowing spidering and indexing of non-www versions of webpages. Recommend 301 redirecting the non-www requests to their equivalent www version.

Options +FollowSymLinks
RewriteEngine on
RewriteCond %{HTTP_HOST} ^example.com[nc]
RewriteRule ^(.*)$ http://www.example.com/$1 [r=301,nc]

301 Redirect File and Folder

You can use .htaccess file to redirect any request for a specific URL to a new URL. Or you can also redirect the entire folder to a new folder location.

//301 Redirect Old File
Redirect 301 <local-path>/OLD-URL.html <local-path>/NEW-URL.html

//301 Redirect Entire Directory
RedirectMatch 301 /old-folder/(.*) /new-folder//$1

Custom Error Pages

Custom Error Page allows you to have your own custom personal error pages instead of using the web hosting provider’s error pages or having no page. This makes a website look very much professional in the unlikely event of an error. Web master can also write scripts to notify him if there is an error.
Example I use a PHP script on to automatically e-mail me when a page is not found.

List of HTTP Response Status Codes. These are some of the most common errors:

  • 400 - Bad request
  • 401 - Authorization Required
  • 403 - Forbidden
  • 404 - Not Found
  • 500 - Internal Server Error
//Custom 400 errors
ErrorDocument 400 <local-path>/error-400.html

//Custom 401 errors
ErrorDocument 401 <local-path>/error-401.html

//Custom 403 errors
ErrorDocument 403 <local-path>/error-403.html

//Custom 404 errors
ErrorDocument 404 <local-path>/error-404.html

//Custom 500 errors
ErrorDocument 500 <local-path>/error-500.html

Preventing directory listing

Preventing directory listing

Stop A Directory Index From Being Shown. Typically servers are setup to prevent directory listing, but often they aren't. If there is a directory full of downloads or images that a web master doesn't want visitors to be able to browse through, add the following line to the .htaccess file.

//Prevent directory listings
Options All -Indexes

//Prevent viewing of .htaccess file
<Files .htaccess>
order allow,deny
deny from all

Alternative Index Files

Webmaster may not always want to use index.html or index.php as the index file for a directory, for example if you are using PHP files in your site, you may want index.php to be the index file for a directory. You are not limited to 'index' files though.

Alternate index files are entered in a list. The server will work from left to right, checking to see if each file exists, if none of them exist it will display a directory listing, unless it have been turned this off.

//Change default directory page
DirectoryIndex home.html default.html main.htm


Making static content cacheable avoids frequent requests for it and improves website performance. Specify expiration of at least one week for static resources.

  • 1 Mins = 60
  • 1 Hour = 3600
  • 1 Day = 86400
  • 1 Week = 36288000
  • 1 Month = 160704000
//Caching Schema 
<FilesMatch "\.(css|js|html|xml|jpg|gif|txt|png)$">
Header set Cache-Control "public, proxy-revalidate, max-age=36288000"

Regular Expressions

  • Patterns ("wildcards") are matched against a string
  • Normal alphanumeric characters are treated as normal
  • Special characters:
    • . (full stop) - match any character
    • * (asterix) - match zero or more of the previous symbol
    • + (plus) - match one or more of the previous symbol
    • ? (question) - match zero or one of the previous symbol
    • \? (backslash-something) - match special characters
    • ^ (caret) - match the start of a string
    • $ (dollar) - match the end of a string
    • [set] - match any one of the symbols inside the square braces.
    • (pattern) - grouping, remember what the pattern matched as a special variable
  • Examples:
    • a+ matches "a", "aaaa", "aaaaaaaaaaaa", but not "bbb"
    • [ab]+ matches, "a", "b", or any length combination of the two
    • \.s?html? matches ".htm", ".shtm", ".html" or ".shtml"
    • (.+)/1999/(.+) matches "subject/1999/psy1011/", and also stores "subject" in $1 and "psy1011/" in $2.
  • Regular expressions are very extensive.
    • Documentation on silas: man regex
    • Friedl (1997). Mastering Regular Expressions. O'Reilly.

A .htaccess is one of the most useful files a webmaster can use. There are a wide variety of different uses for it which can save time and increase security on your website.

Note for Windows users
Notice that the file name starts with a period (.). This is to indicate to the Linux/Unix operating system that it is a system file that is used by a server application, not by a user of the system. However, with Windows, the period denotes a separator between a file's name and its extension. As a result, if you try and create an .htaccess file in Windows it won't have a name. To get around this, create a file called htaccess.txt, ftp that to the server, and then rename it to .htaccess once it's there.

Add a comment

About the Author
Joydeep Deb

is a Senior Digital Marketer and Project Manager with 15+ years of experience in Digital Marketing, Lead Generation, Online Brand Management, Marketing Campaigns, Project Management, Search Engine Optimization (SEO), Search Engine Marketing (SEM), PPC, eMail Marketing, Web Analytics, Web Technologies, Web Design and Development.

With an MBA in Marketing. IIM Calcutta Alumini. Lives in Bangalore, Karnataka - India.

Get social with Joydeep at Twitter | Facebook | LinkedIn