The Apache Sever’s mod_rewrite module gives you the ability to change the URL or redirect the URL transparently without displaying it to the user.
http://localhost/test/index.php TO http://localhost/test/home etc..
Such type of URL Rewriting is very helpful for Search Engine Optimization (SEO).
.htaccess file is created to Rewrite the URL etc. It can be used to perform many functionalities redirect URLs, clean dirty, you can create password protected directories, and many many more… But in this tutorial, we’ll discuss only about the URL Rewriting (URL Redirecting).
To use mod_rewrite, you set the link text you want to server to match and the original URLs. The original URLs will be redirected to the link text you set.
To use .htaccess file in your project mod_rewrite should be enabled. You’ve to enable it manually if you are working locally. If you are using WAMP/XAMP the goto WAMP-> Apache->Apache modules -> mod_rewrite… If you are not using WAMP/XAMP you can google about it..
Lets Start the Basic Example.
You have the url http://localhost/test/index.php and you want to change it with http://localhost/test/index.html
to do this, open notepad, and save the file in your project directory with the name .htaccess
Note: select All files from save as type while saving the .htaccess file..
You can enable Rewriting by including this line in the file..
Now to rewriting the complete code will be..
RewriteRule ^index\.html$ index.php
Now open the url http://localhost/test/index.html..
There are three special characters in there.
- The caret,
^, signifies the start of an URL, under the current directory. This directory is whatever directory the .htaccess file is in. You’ll start almost all matches with a caret.
- The dollar sign,
$, signifies the end of the string to be matched. You should add this in to stop your rules matching the first part of longer URLs.
- The period or dot before the file extension is a special character in regular expressions, and would mean something special if we didn’t escape it with the backslash, which tells Apache to treat it as a normal character.
Now we get on to the really useful stuff. The power of
mod_rewrite comes at the expense of complexity. If this is your first encounter with regular expressions, you may find by googling about Regular Expressions
Using regular expressions you can have your rules matching a set of URLs at a time, and mass-redirect them to their actual pages. Take this rule;
RewriteRule ^products/([0-9][0-9])/$ /product.php?pid=$1
This will match any URLs that start with ‘products/’, followed by any two digits, followed by a forward slash. For example, this rule will match an URL likeproducts/12/orproducts/99/, and redirect it to the PHP page.
RewriteRule ^products/([0-9][0-9])/$ /productinfo.php?prodID=$1
There are plenty of rewriting rules that can be applied..
I’ll discuss about it with more detail in my next tutorial..