Url Rewriting using php, smarty and mod_rewrite


Let’s learn to rewrite the website url today.

According to me, before learning something new, we should take a look at why we need to do it and what’s the use of it.

Use of URL rewriting:
1. Making website URLs more user and search engine friendly.
2. Preventing undesired “inline linking”.
3. Not exposing the inner workings of a web site’s address to visitors

So let’s begin…

Project Name: url_rewriting
Dir. Structure: url_rewriting
– cache
– configs
– libs
– templates
– templates_c
– .htaccess
– other php files

What we want to achieve:
here we want to convert the following url
from,
http://www.orkut.com/UniversalSearch.php?origin=box&exp=1&q=php
to
http://www.orkut.com/box/1/php/UniversalSearch.html

How we can achieve:
we need to first create a file “function.seo_optimise.php” in “smarty/lib/plugins/”, so that smarty will treat it as its own function without any hassal.

function smarty_function_seo_optimise($params, &$smarty)
{
// we will add code here later...
}

Done… 50%

Now secondly, we have to create a .htaccess file in the directory structure as shown above. And add following…


php_value error_reporting 7
Options +FollowSymLinks
RewriteEngine on
RewriteRule ^(.*)/([0-9]+)/(.*)/UniversalSearch.html$ UniversalSearch.php?origin=$1&exp=$2&q=$3


Please note that, (.*) suggest the type of text we are sending to perticular querystring. Like for origin querystring, we are going to send anything including characters & numbers, or in case of exp querystring, we are going to send only numbers thats why we have used ([0-9]+) in order to restrict the querystring value to the numbers only.

Done... 70%

I know, you are confused now, because you are thinking that how smarty will know, (.*) for origin, ([0-9]+) for exp and (.*) for q. Do not worry, thats we have created "function.seo_optimise.php" file above. Now, open this file, and write the following code... please note that here we are going to send three querystrings to the page thats why we have to pass three parameters to the function also. These are the three parameters..

function smarty_function_seo_optimise($params, &$smarty)
{
    /* This is for three querystrings */
        $origin =  $params[origin];
        $exp     =  $params[exp];
        $q         =  $params[q];
   /* This is to recognise the page to which we are going to rewrite */
   if($params[type] == 'universal_page')
   {
       if($params[urls] == 'Enable')
           return $origin."/".$exp."/".$q."/UniversalSearch.html";
       else
           return "UniversalSearch.php?origin=".$origin."&exp=".$exp."&q=".$q
   }
}


Done... 80%

Now let me explain you, this smarty function will transform our old url to new like this... http://www.orkut.com/box/1/php/UniversalSearch.html Ok then, time to spell the beans... to convert that url we have to write following in .tpl file.

{seo_optimise urls=$seo_urls origin=box exp=1 q=php type=universal_page}

<a href="http://www.blogger.com/%7Bseo_optimise%20urls=$seo_urls%20origin=box%20exp=1%20q=php%20type=universal_page%7D">
Click me
</a>

here is a explaination...

$seo_urls => Enable/Disable

when the page get loaded, that seo_optimise will pass the supplied parameters to the function of a same name created in smarty/lib/plugins/function.seo_optimise.php.

1. First, it will add the passed value to appropriete variables as mentioned above in this php file.
2. secondly, it will check which page you want to rewrite using "type" variable.
3. If it is "universal_page" and $seo_urls is "Enable" then it will return the url like http://www.orkut.com/box/1/php/UniversalSearch.html or if $seo_urls is "Disable" then it will return the url like http://www.orkut.com/UniversalSearch.php?origin=box&exp=1&q=php
Done... 100%

Using this way we can rewrite any url in any ways you want, just do not forget to enter the old url & new url in .htaccess file.

36 thoughts on “Url Rewriting using php, smarty and mod_rewrite

  1. I used RewriteRule until I had to develop a system where you could edit the mod_rewrite links, which required that I edit .htaccess every time I wanted to change the way the links looked. So I stuck to the drupal way of mod_rewrite usage in that case. However, if you do not need to be able to change the way links look after mod_rewrite, then the way you described is ideal.

  2. Hi,

    Thanks for your article.

    Do I understand it correctly that it will automatically transform my links to seo friendly links?

    That doestn work.
    When I go to UniversalSearch.html manually, it shows a 404 error.

    Then some other things: Where should I implement $seo_urls => Enable/Disable ?

    I have my rewrite rule in .htaccess

    RewriteRule ^(.*)/(.*)/overview.html $
    index.php?label=$1&checkout=$2

    the function:
    function smarty_function_seo_optimise($params, &$smarty)

    {
    /* This is for three querystrings */
    $origin = $params[origin];
    $exp = $params[exp];

    /* This is to recognise the page to which we are going to rewrite */
    if($params[type] == ‘overview’)
    {
    if($params[urls] == ‘Enable’)
    return $origin.$exp.”/overview.html”;
    }
    else
    {
    return “index.php?label=”.$origin.”&checkout=”.$exp;
    }

    }

    This is in the URL line
    index.php?label=cart&checkout=overview

    Hope u can help

  3. Hi Danny,

    This is the way you have rewritten your URL
    RewriteRule ^(.*)/(.*)/overview.html $ index.php?label=$1&checkout=$2

    but there is no slashes (/) to separate the querystrings, here..
    return $origin.$exp.”/overview.html;
    this should be like
    return $origin.”/”.$exp.”/overview.html

    Even if it will not work, then try to put this in your tpl file…
    {seo_optimise urls=Enable origin=cart exp=overview type=overview}
    this will print your rewritten URL, “cart/overview/overview.html”
    so you can compare it with the one defined in .htaccess file.

    And finally, you can set $seo_urls value i.e. Enable/Disable in DB or in a Global Variable too.

    I hope this will help you. Thank you for your comment.

  4. Hi amitgharat,,

    Thanks a lot for your reply.

    I already found out that it worked with

    return $origin.”/”.$exp.”/overview.html

    If I understand it correctly.
    The function is only to print out the rewritten url?

    What about automatically redirect the page to the rewritten url?

    so the url index.php?label=cart&checkout=overview will be automatically redirected.

    I tried to do this with a header location function, but it got stuck in an endless loop.

    Do u have a solution for this?

    Kind regards

    Danny

  5. i solved this problem by putting hidden input field in a webpage which will have the rewritten URL of index.php.
    So, in this case i use javascript instead of header PHP function as,

    window.location.href = document.getElementById(‘hidden_input_id’).value

    • Thank your article,it is very helpfull, I write code follow code of you and I already outputed url rewrite
      but i dont understand how to you use window.location.href = document.getElementById(‘hidden_input_id’).value?
      because my web user smarty template for whmcs?
      Can yu help me?

      • I’m not sure whether you need that JS code or not. Thats basically required to forward user to particular page after some activity such as button click and you can use smarty php code to rewrite a url inside script tag.

  6. hi amit
    its my .htaccess file

    php_value error_reporting 7
    Options +FollowSymLinks
    RewriteEngine on
    RewriteRule ^index.php$ index.php [NC]
    RewriteRule ^(.*)/database_migration.php$ database_migration.php?mode=$1 [NC]

    //seo optimise function
    function smarty_function_seo_optimise($params, &$smarty)
    {
    if($params[type] == ‘database_migration_page’)
    {
    if($params[seo] == ‘Enable’)
    return $page_mode.”/”.$page_name.PAGE_EXTENSION;
    else
    return $page_name.”.php?mode=”.$page_mode.”&id=”.$id;
    }
    }

    it will rewrite the url but getting error page not found?

  7. Hi
    thanks for ur article.

    Would you please suggest me for .htacces and seo function for dynamic return url. ie some pages have 3 requirements and some has 4.
    eg:
    website.com/about_us
    website.com/about_us.id=12 like this continous

    Jeyabalan

    • AFAIK, you can not do it dynamically. But you can send multiple query strings in a go.
      eg. `website.com/about_us?id=1&val=2` and you have defined url in .htaccess like `(*.*)/about_us$`
      For single query string, u can use `website.com/1/about_us`
      For multiple query strings, u can use `website.com/1@2/about_us` P.S. You can use any other separator like | (pipe), ,(comma) etc
      Finally u have to explode that query string with the separator specified.

      I hope, it will be helpful for you.

  8. Hi
    Thanks a lot for your reply.
    My problem is .htacces for website redirect url for dynamic pages.

    e.g
    website.com/about_us [one page]
    website.com/product?id=1&val=2[2nd page]

    index.php?module=”.$module.”&action=”.$action.”&type=”.$q

    • Well, i did not get your point. Based on what i understood, i m explaining the thing:

      2nd URL can have 2 or more querystrings as u mentioned.
      So in this case for a url having 2 querystrings, u can use: {seo_optimise qs=$var1@$var2 type=product_page}

    • You need to put below in your .htaccess file:

      
      RewriteRule ^(.*)$ index.php?categoryID=1$
      
      

      and in seo_optimise.php file:

      
      function smarty_function_seo_optimise($params, &$smarty)
      {
          /* This is for three querystrings */
              $categoryID =  $params['categoryID'];
        
         if($params['type'] == 'index_page')
         {
                 return "Your website path goes here/".$categoryID;
         }
      }
      
      

      But once the user visits, your-website-path/categoryID1 page, you will have to fetch category id based on a name passed as a querystring. This will only work in case of unique category name.

      P.S. WordPress also saves hyphenated title of a post in the database as a unique id, so they can use it in URL instead of using post id.
      e.g. https://amitgharat.wordpress.com/2008/06/18/url-rewriting-using-php-smarty-and-mod_rewrite/

  9. Its such as you read my thoughts! You seem to know a lot approximately
    this, like you wrote the e book in it or something.
    I believe that you simply could do with some percent
    to power the message house a bit, however instead of that, this is magnificent blog.
    A fantastic read. I will definitely be back.

  10. Hello amit, your article is very helpfull. I have a question regarding this type of url re-writing.. suppose i have a link that carries a product id and targeted to product page, now i want to show the category name, subcategory name and product name in the url. like ‘oral-care/tooth-paste/colgate-25gm’, where oral-care is category name followed by sub-category name followed by product name. These category,sub-category and product id are stored in our database. Can you please give a guideline how to achieve it?

  11. Hi amit, your article is a good one to follow. I am doing a smarty project where there are huge number of pages. Among those one is http://www.healthgurulive.com/community_mgt_full.php?a=168. I want this is to be shown as http://www.healthgurulive.com/customers-administered-community-to-test-blogs-within-a/doctor-joins-community-and-writes-a-blog-post, where ‘customers-administered-community-to-test-blogs-within-a’ is a community category and ‘doctor-joins-community-and-writes-a-blog-post’ is a community name and in the first url where ‘a=168’ is the community id. These are coming from our database. Kindly guide me to achieve it. Thanks.

  12. Hello amit, your article is very helpfull. I have a question regarding this type of url re-writing.. suppose i have a link that carries a product id and targeted to product page, now i want to show the category name, subcategory name and product name in the url. like ‘oral-care/tooth-paste/colgate-25gm’, where oral-care is category name followed by sub-category name followed by product name. Can you please give a guideline how to achieve it?

  13. Thanks,
    I have another question, now i want to url rewrite from mydomain/news.php
    url rewrite to
    mydomain/new-paper or mydomain/news.html

    Many thanks!

    • It’s already mentioned in the blog post. You need to set up urlRewrite in .htaccess file as per your requirement and then modify the smarty plugin accordingly.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.