.htaccess stands for hypertext access. It is the default name of Apache directory-level configuration file. .htaccess file provides a way to make configuration changes on a per-directory basis. .htaccess file is placed in a particular directory and the directives in the .htaccess file apply to that directory and all subdirectories thereof.The filename starts with a dot because dot files are by convention hidden files on Unix-like operating systems.
A few general ideas
In order to create the file, open up a text editor and save an empty page as .htaccess (or type in one character, as some editors will not let you save an empty page).
.htaccess files must be uploaded as ASCII mode, not BINARY. You may need to CHMOD the htaccess file to 644 or (RW-R–R–). This makes the file usable by the server, but prevents it from being read by a browser, which can seriously compromise your security. (For example, if you have password protected directories, if a browser can read the htaccess file, then they can get the location of the authentication file and then reverse engineer the list to get full access to any portion that you previously had protected. There are different ways to prevent this, one being to place all your authentication files above the root directory so that they are not www accessible, and the other is through an htaccess series of commands that prevents itself from being accessed by a browser, more on that later)
Most commands in htaccess are meant to be placed on one line only, so if you use a text editor that uses word-wrap, make sure it is disabled or it might throw in a few characters that annoy Apache to no end, although Apache is typically very forgiving of malformed content in an htaccess file.
htaccess files affect the directory they are placed in and all sub-directories, that is an htaccess file located in your root directory (yoursite.com) would affect yoursite.com/content, yoursite.com/content/contents, etc. It is important to note that this can be
prevented (if, for example, you did not want certain htaccess commands to affect a specific directory) by placing a new htaccess file within the directory you don’t want affected with certain changes, and removing the specific command(s) from the new htaccess file that you do not want affecting this directory. In short, the nearest htaccess file to the current directory is treated as the htaccess file. If the nearest htaccess file is your global htaccess located in your root, then it affects every single directory in your entire site.
Also…some sites do not allow use of htaccess files, since depending on what they are doing, they can slow down a server overloaded with domains if they are all using htaccess files. I can’t stress this enough: You need to make sure you are allowed to use htaccess before you actually use it. Some things that htaccess can do can compromise a server configuration that has been specifically setup by the admin, so don’t get in trouble.
In general, you should never use .htaccess files unless you don’t have access to the main server configuration file. There is, for example, a prevailing misconception that user authentication should always be done in .htaccess files. This is simply not the case. You can put user authentication configurations in the main server configuration, and this is, in fact, the preferred way to do things.
The use of .htaccess files effects performance. When AllowOverride is set to allow the use of .htaccess files, Apache will look in every directory for .htaccess files. Thus, permitting .htaccess files causes a performance hit, whether or not you actually even use them! Also, the .htaccess file is loaded every time a document is requested.
.htaccess files are very popular and common among web administrators or server administrators as they provide various configuration settings for them. .htaccess files are commonly used for
- Authorization and Authentication to specify the security restrictions for a particular directory.
- Redirect users from one page to another using Apache mod_rewrite.
- Prevent directory browsing.
- Change the default index page of a directory.
- Block various bots.
- Presenting custom error pages
Authorization & Authentication
.htaccess files are often used to specify the security restrictions for a particular directory, hence the filename “access”. The .htaccess file is often accompanied by a .htpasswd file which stores valid usernames and their passwords.
You must have “AllowOverride AuthConfig” in effect for these directives to be honored.
Contents of .htaccess file to provide authentication for a directory
AuthType Basic
AuthName "Password Required"
AuthUserFile /www/passwords/password.file
AuthGroupFile /www/passwords/group.file
Require Group admins
Note that AllowOverride AuthConfig must be in effect for these directives to have any effect.
Redirect users from one page to another
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.
Using mod_rewrite rules
This is an Apache module which provides rule based rewriting engine to rewrite requested URLs on the fly. It supports an unlimited number of rules and an unlimited number of attached rule conditions for each rule to provide a really flexible and powerful URL manipulation mechanism. The URL manipulations can depend on various tests, for instance server variables, environment variables, HTTP headers, time stamps and even external database lookups in various formats can be used to achieve a really granular URL matching.
This module operates on the full URLs (including the path-info part) both in per-server context (httpd.conf) and per-directory context (.htaccess) and can even generate query-string parts on result. The rewritten result can lead to internal sub-processing, external request redirection or even to an internal proxy throughput. But all this functionality and flexibility has its drawback: complexity. So don’t expect to understand this entire module in just one day. This module was invented and originally written in April 1996 and gifted exclusively to the The Apache Group in July 1997 by <a href=”http://www.engelschall.com” target=”_blank”>Ralf S. Engelschall</a>
Examples of mod_rewrite
1. Description – Your current pages are called using index.php with parameter of url i.e
http://www.example.com/index.php?url=category
and instead of this URL, you want a nice and easy to read URL like http://www.example.com/category
Solution – Put the following lines in your .htaccess file.
RewriteEngine on
RewriteRule ^([^/.]+)/?$ /index.php?url=$1 [L]
Note: If your file already contains a line ‘RewriteEngine on’ then you don’t need to put it again unless it was set to off before you putting in your lines.
2. Description – Your current URL is
http://www.example.com/index.php?cat=category&subcat=subcategory
which you would like to see as
http://www.example.com/category/subcategory
Solution – Put the below lines in your .htaccess file
RewriteEngine on
RewriteRule ^([^/.]+)/([^/.]+)/?$ /index.php?cat=$1&subcat=$2 [L]
3. Description – You want to have many sub categories or categories like
http://www.your-domain.com/category/subcat1/subcat2/subcat3/subcat4/subcat5/
which you would to rewrite to
http://www.your-domain.com/index.php?cat=category&subcat1=subcat1&subcat2=subcat2 and so on …
Solution – See below lines..
domain.com/category –> index.php?cat=category
RewriteRule ^([^/.]+)/?$ /index.php?cat=$1 [L]
domain.com/category/subcategory/ –> index.php?cat=category&subcat=subcategory
RewriteRule ^([^/.]+)/([^/.]+)/?$ /index.php?cat=$1&subcat=$2 [L]
domain.com/p1/p2/p3/ –> index.php?a=p1&b=p2&c=p3
RewriteRule ^([^/.]+)/([^/.]+)/([^/.]+)/?$ /index.php?a=$1&b=$2&c=$3 [L]
domain.com/p1/p2/p3/p4 –> index.php?a=p1&b=p2&c=p3&d=p4
RewriteRule ^([^/.]+)/([^/.]+)/([^/.]+)/([^/.]+)/?$ /index.php?a=$1&b=$2&c=$3&d=$4 [L]
4. Description – Your URL has a folder and you would like rewriting for that folder. The URL looks like this http://domain.com/folder/index.php?url=name which you want to see as http://domain.com/folder/name/
Solution – Place the following lines in your .htaccess file
RewriteEngine on
RewriteRule ^folder/([^/.]+)/?$ folder/index.php?url=$1 [L]
5. Description – Your actual URL is http://example.com/index.php?page=hello which you want to see as http://example.com/hello.htm
Solution – Place the following lines in your .htaccess file
RewriteEngine on
RewriteRule ^([^/.]+).htm$ index.php?page=$1 [L]
6. Description – Your URL is http://example.com/folder/index.php?page=hello which you want to see as http://example.com/folder/hello.htm
Solution – Place the following lines in your .htaccess file
RewriteEngine on
RewriteRule ^folder/([^/.]+).htm$ folder/index.php?page=$1 [L]
There are many more things that you can do with mod_rewrite. As and when I discover more examples, I will keep updating this page. Please feel free to post your usage of mod_rewrite if already not covered here and I will add them to the above list of examples.
Prevent 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
Change the default index page of a directory
Apache configuration file by default contains various file formats with index as filename as defaults for the index page. So, in case your site or directory does not has a file name which is included by default, 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
Remember, each entry must be in one line only.
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.
Presenting custom error pages
Use .htaccess file to present users with your custom pages for 401 [Authorization Required], 403 [Forbidden], 404 [not found] and 500 [Internal Server Error].
Syntax:
ErrorDocument < error-code > < location -of-custom-page>
Examples:
ErrorDocument 401 /401.html
ErrorDocument 403 /403.html
ErrorDocument 404 /404.html
ErrorDocument 500 /500.html
You can include some script in your customized pages to automatically send an email to you whenever those pages are called for. This way you will be notified every time a user encounters 404, 500 and other error messages.
Allow/Disallow certain visitors from accessing your site
To accomplish it use the following lines. Look at the syntax first:
Syntax:
Order allow,deny
Deny from < incoming -address >
Allow from < incoming -address>
The first line [Order allow,deny] tells what should be done first. The second line tells about denying incoming-addresses [could be a single IP, an IP block, domain name and all] and third line tells about the incoming-addresses [could be a single IP, an IP block, domain name and all] those should be allowed. If second line has ‘Deny all’, then you should change the order of allow,deny in the first line to deny,allow.
To deny access to a single IP address and allow everyone else
Order allow,deny
Deny from 100.100.100.1
Allow from all
To deny a block of IP address and allow everyone else. [Notice the second line]
Order allow,deny
Deny from 100.100.100.
Allow from all
To deny a single IP address and allow everyone else. [Use it to block referrals from a specific domain]
Order allow,deny
Deny from www.my-domain.com
Allow from all
3 Responses to All about .htaccess files
-
Arselan Says:November 26th, 2008
Really nice dude I was not able to understand the funda of .htaccess but you helped me.
Keep it up. I am lovin it. -
Jeremy Says:November 26th, 2008
Great Info!! .htaccess is very powerful but can be tough at first.
A pretty cool .htaccess file I use which is used to prevent random web browsers from accessing folders directly, while allowing them to be accessed via your site. Bassically if someone tried to access yoursite.com/vidoes/1.wmv or something, they would be redirected to a page you specify. But if you had a link at yoursite.com when a user clicks on it takes them to yoursite.com/videos/1.wmv would be allowed. This prevents access to folders/directories and even if a person was to guess the link they wouldn’t be able to access it unless they first came through your site.
I did test this with ie and firefox and it seems to work great in each.
Code:
AuthUserFile /dev/null
AuthGroupFile /dev/nullRewriteEngine On
RewriteCond %{HTTP_REFERER} !^http://www.yoursite.com.* [NC]
RewriteCond %{HTTP_REFERER} !^http://subdomain.yoursite.com.* [NC]
RewriteCond %{HTTP_REFERER} !^http://.yoursite.com/subfolder.* [NC]
RewriteCond %{HTTP_REFERER} !^http://yoursite.com.* [NC]
RewriteCond %{HTTP_REFERER} !^http://www.yoursite.com/subfolder.* [NC]RewriteRule /* http://www.yoursite.com/index.php [R,L]
Just create a .htaccess and insert that code into any subfolder/directory you don’t want anyone to directly access without coming through your site. like yoursite.com/videos/.htaccess (with the above code)
RewriteCond = yoursite.com (this is your site, subdomains, and subfolders allowed to access)
RewriteRule = the address they are forwarded to if they try to access directly.Jeremy
dialme.com -
Adrian Says:November 26th, 2008
Hi I have a problem that I read could be fixed with a rewrite as follows:
TikiWiki 2.2: The “Multimedia” feature requires a “url” parameter, which is damaged to uXrl by XSS protection. TikiWiki has no way to play MP3 files (XSPF mod seems nonfunctional in 2.1).
{FLASH(movie=>”tikimovies/multiplayer.swf?url=http://yoururl/file.mp3&MODE=AUDIO”)}{FLASH}
Hack workaround: Add a URL rewrite rule to .htaccess which changes a “hack=” parameter to “url=”.
Do you know how I can do this?

