URL rewriting using htaccess

.htaccess rewrite are enabled by using the Apache module mod_rewrite, which is one of the most powerful Apache modules and features available. It helps to manipulate the links such that we  can transform  very long URL’s into short, cute URLs, transform dynamic URL’s like index.php?page=news, news.php?id=10  into SEO friendly and clean format, redirect missing pages, prevent hot-linking, perform automatic language translation, Deny/Allow certain IP/IP Range and many more.

To use this feature mod_rewrite needs to enabled, for e.g.  in xampp:

Go to the xampp/Apache/conf/httpd.conf   – search for mod_rewrite and you will get the line:

#LoadModule rewrite_module modules/mod_rewrite.so

Remove the # from the line and save it, then restart the Apache.

Now create a file .htaccess in the root directory and include the following,

Example 1:

Options +FollowSymlinks

RewriteEngine on

RewriteRule ^(.*)\.html$  $1.php [NC]

Where, $1 -> first back-reference,  NC -> No Case

With this rule any file with .php extension rewrite to .html , e.g. news.php -> news.html

Example 2:

Options +FollowSymlinks

RewriteEngine on

RewriteRule ^([a-zA-Z0-9_]+)\.html$  index.php?page=$1

This rule rewrites URL like index.php?page=contact_us  into contact_us.html

Using in PHP code: While using in the php code we must write the href link as contact_us.html instead of



<a href="<?php echo 'www.domain.com/'.'contact_us'.'.html';?>"> Contact Us </a>

Example 3:

Options +FollowSymlinks

RewriteEngine On
RewriteRule ^([a-zA-Z0-9_-]+)$  account.php?id=$1
RewriteRule ^([a-zA-Z0-9_-]+)/$  account.php?id=$1

This rule rewrites the URL like http://www.domain.com/account.php?id=54  into  http://www.domain.com/54


  1. If any error occurs with .htaccess  file then Internal server error in displayed. The rules can be commented by adding # in front of line.
  2. No two  rules for same back-reference will work, that means a rule defined for single back-reference is enough, so you can have another rule for two back-reference.
Be Sociable, Share!
You can leave a response, or trackback from your own site.

2 Responses to “URL rewriting using htaccess”

  1. CSS Coder says:

    This is a code that i am looking for. :-)

    CSS Coder

  2. Oh my goodness! Incredible article dude! Thank you
    so much, However I am having problems with your RSS.

    I don’t know why I cannot join it. Is there anybody else getting the same RSS issues?
    Anybody who knows the solution will you kindly respond? Thanx!!

    Visit my site … website design durban
    website design durban recently posted..website design durban

Leave a Reply

CommentLuv badge

Powered by WordPress