A Really Simple Tutorial - To Understand And Implement Dynamic URL Re-Writing or commonly known as canonical/pretty URLs

Nishant Arora 05/Dec/2011
Facebook
Twitter
LinkedIn
Reddit

Working on developing websites makes you learn many things, well almost all of it, and today while working on one of my websites I realized how easy implementing canonical or pretty URLs was. I learnt this art a few years ago, and today while writing it for one of my own website I realized well yeah, this is easy, this is nice, this can be easily shared.

So before understanding how to implement let us learn how this works (Please this is just an example so do not take it seriously), and what are we expecting off it. Just go to the URL here:

http://nishantarora.in/url_tut/index.php?name=Mr.%20Bond&sex=Male&phone=9999000777

But, all these variables going in like this (For those who do not know, name, sex and phone are variables and will change the page accordingly!) looks so poor, so what do we do?

We can use the server's configuration files stored in the .htaccess to make this happen, we can rewrite the URL dynamically as and when page loads to look something like:

//display----details.html

so the given URL becomes:

http://nishantarora.in/url_tut/display-Mr.%20bond-male-999999999-details.html

Yes it does work, and you can change the values and generate any number of html pages you like, so it can be like anything in that position lets say (my favourite):

http://nishantarora.in/url_tut/display-Crime%20Master%20GoGO-Sucker-9420420420-details.html

which was earlier like

http://nishantarora.in/url_tut/index.php?&name=Crime%20Master%20GoGO&sex=Sucker&phone=9420420420

This was a nice decision, looks nice, so how to get this implemented.

  1. Open/Create ".htaccess" file, in which the php to be dealt with exists
  2. insert the following code in the file:
    <IfModule mod_rewrite.c>
    RewriteEngine on
        RewriteRule ^display-(.*)-(.*)-(.*)-details.html?$ index.php?&amp;name=$1&amp;sex=$2&amp;phone=$3 [L]
    </IfModule>
  3. save it you are done.
How does this works?
the code "RewriteRule ^display-(.*)-(.*)-(.*)-details.html?$ index.php?&name=$1&sex=$2&phone=$3 [L]" does the job, "(.*)" represents the positions in the new URL, and where according to their appearing order are to be placed in the original URL, it is depicted by $1, $2,$3 and so on. "[L]" acts a delimiter as ; or } acts in PHP/C/C++ and JS respectively!
Hope it helps you do something new!
Enjoy!
I would love to hear from you!