.htaccess files (or “distributed configuration files”) provide a way to make configuration changes on a per-directory basis. In simple words, htaccess allow you to override the default server configuration using certain commands. htaccess file works in Apache Web Server on both Linux/Unix and Windows operating system. This post has some basic example and method to create and use htaccess commands. Use of htaccess is simple, if your goal is clear what you want to do with it.
Tasks that can be perform with htaccess -
* Allow/Deny directory browsing
* Display SEO friendly URLs (URL Rewrite).
* Change the default index page of a directory or site
* Redirecting pages / sites temporary or permanently
* Define custom error pages
* Enabling SSI (server side includes)
* Deny/Allow IP addresses
* Password protecting directories
* Caching
How to create .htaccess files
Creating .htaccess file is simple. You can create it with any text editor like notepad or dream weaver etc. .htaccess is just an extension so while creating you need to give only extension “.htaccess”.
To create .htaccess file, simply open new blank document in your text editor and save it as .htaccess. Some text editors ask for file name and not allow to store extension only. For this you can give it some name like 1.htaccess or anything else. After uploaded to server, you can rename it to .htaccess through your FTP client.
Allow/Deny directory browsing
If you don’t have index or default page in your directory then it will list all the files and folder of that directory. This could be a security risk for your site.
Example :
To prevent such directory access, just place the following line in your .htaccess file.
IndexIgnore */*
or
Options -Indexes
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
Display SEO friendly URLs
This is one of the most useful feature of htaccess. Now a days most website using this technique to convert complex urls into simple SEO friendly urls. Search engines ignores dynamic url after “?” therefore need to convert it into static, more search engine readable format.
URL rewriting needs -
To rewrite the URL you must have the mod_rewrite module must be loaded in Apache server.
Example :
Write below lines in your htaccess.
Options +FollowSymlinks
RewriteEngine on
RewriteRule ^news/([0-9]+).html/?$ news.php?news_id=$1
Here $1 represents dynamic ids of news. Now link will appear as SITE_URL/news/1 instead of SITE_URL/news.php?news_id=1
Make sure you made changes in php file where you have your code -
<a href="news/<?php echo $news_id;?>.html">News Link</a>
Similarly you can change complex urls into SEO friendly urls.
Change the default index page of a directory or site
If your directory have index.htm, index.html, index.php, default.html as the default index page and you want to change it then you can do it with the following command in htaccess.
Example :
DirectoryIndex mypage.html
DirectoryIndex smartcoderszone.html
You can mention more then one page in listing with space between them. It will search for matching index page name in the list of names then it will open that page as the index page for the directory.
DirectoryIndex mypage.html yourpage.html mynewpage.html bethebest.html
Create server side redirects
There are some conditions when you want to move your site to new domain or move some pages from root folder to inner directory. In this situation, you should create permanent redirects (301 redirects).
Types : There are two types of redirect -
1. 301 or permanent redirects.
2. 302 or temp redirects.
Benefits : This command not only redirect visitors to new location but also to tell search engines that location has been changed permanently. This technique will also preserve website rankings.
302 redirect useful in case of affiliate program where direct affiliate link might not be a secure way. 302 prevents this from happening and to make your affiliate links according to you.
Examples :
In the .htaccess file of the old domain you would put the following line to redirect all traffic from the old location to your new location.
redirect 301 / http://www.newdomain.com
if you want to change location of your files from root to inner directory.
redirect 301 /old_location.html http://www.yourdomain.com/inner_foldername/new_location.html
if you want to make your affiliate link secure, use temp redirects -
redirect 302 /sponsor http://www.sponsor-bank.com?user_id/sponsor
Define custom error pages
You can define your own error pages that will make your site more interactive. Custom error occurs when some one trying to access pages that are no longer available. Some common errors -
401 – Authorization Required (try to access password protected pages)
403 – Forbidden (try to access file with not sufficient file permission)
404 – Not Found (try to access page that does not exists)
500 – Internal Server Error
You can give any name to your custom page that should be relative to error.
Example :
ErrorDocument 401 /401.html
Enable SSI on static webpages
SSI (server side includes) provides way to include dynamic contents on specific parts like header, footer etc of all your static webpages’s source code before delivered to visitor.
SSI can include different types of contents in your web pages like CGI scripts, server date and path variables, php scripts and html code.
Note : Your web hosting must support SSI.
To enable SSI on static .html and .htm webpages, you need to add the following line to your .htaccess file.
AddHandler server-parsed .html .htm
Example :
Inside the source code of your web pages, you need to place the include commands within a comment tag in the location where you want the content to be inserted.
to include the content of a different file
Deny/Allow Certian IP Addresses
This feature useful in conditions where you want to allow/deny people with specific IP addresses.
Example :
You can block an IP address by using:
deny from 000.000.000.000
where 000.000.000.000 is the IP address. If you only specify 1 or 2 of the groups of numbers, it will block whole range. Similarly you can allow an IP address by using:
allow from 000.000.000.000
Password protecting directories
Adding password protection to a directory using .htaccess is simple. First write appropriate lines to your .htaccess file in the directory you would like to protect.
Example :
Everything below this directory will be password protected:
AuthName “Section Name”
AuthType Basic
AuthUserFile /full-path-to/.htpasswd
Require valid-user
You should replace “Section Name” with the name of the part of the site you are protecting. The /full-path-to/.htpasswd should be changed to reflect the full server path to the .htpasswd file
Secondly create .htpasswd file and insert username and password in it. Remember your password must be encrypted.
username:password
where the password is the encrypted format of the password. To encrypt the password you will either need to use one of the scripts available on the web or write your own. There is a good username/password service at the KxS site which will allow you to enter the user name and password and will output it in the correct format.
Caching
Making static content cache-able 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
Make sure mod_expires and mod_headers module in your Apache server should be on.
Example :
<FilesMatch "\.(css|js|html|xml|jpg|gif|txt|png)$">
Header set Cache-Control “public, proxy-revalidate, max-age=36288000″
</FilesMatch>
You can use mod_expires to take care of expires and max-age, and use mod_headers to “manually” configure the following:
Cache-Control: no-store This object may not be stored in any cache, even the requestor’s browser cache. Cache-Control: no-cache This object may be held in any cache but it must be revalidated every time it is requested. Cache-Control: private This object can be stored in the requesting browser´s cache but not in a shared cache … Cache-Control: must-revalidate Tells caches that they must obey any freshness information you give them about an object. The HTTP allows caches to take liberties with the freshness of objects; by specifying this header, you’re telling the cache that you want it to strictly follow your rules. Cache-Control: proxy-revalidate Similar to must-revalidate, except that it only applies to proxy caches.
A .htaccess is one of the most useful file a web developer can use. There are a wide variety of different uses for it which can save time and increase security on your website.
Hope this tutorial will give you an idea of how different ways, you can use htaccess.
Cheers!!


November 2nd, 2011 at 6:30 am
Whoh! A complete guide to .htaccess
Great article mate! Thanks!