URL Rewriting in Magento

URL Rewriting in Magento

It is critically important for all the websites to have URLs friendly to serve SEO purpose. However it is not always easy for us to create those in Magento especially when you install a module. How can we tackle this problem as of a non-technical user? We provide 2 feasible solutions for URL Rewriting in Magento and create appropriate URLs as you want. You see it will not a big issue any longer.

Before we approach to the 2 solutions, we are showing an example to describe how a default URL is created and prerequisite knowledge to hatch some repairing. Eg. We created a module for Blog named Blog and its namespace is MGS with simple fields as

         id             title  description

In the back-end, when we create a post we need to insert two fields, ie. Title and Description. ID of the post will be auto-generated. In order to display post details of the Blog we rely on router (declared in file config.xml, we declared blog), controller (we named index, so it will be file IndexControler.php in folder controllers), action (we called view, viewAction function in file IndexControler.php) and id of the post.

So, default URL of the post at front-end will look like this:

http://domain.com/blog/index/view/id/1 (1 is ID of the post)

As far as we can see this URL is totally not good for SEO, it should be rewritten to turn into a URL friendly. Back to the main objective, we proposed 2 methods to create URL friendly. And in either ways you will need to define URL you want or you will follow a common rule to create the URL (usually we will use the title of the post, convert all characters into normal style, replace empty space with -, eg. Title “How to rewrite url in Magento” will become “how-to-rewrite-url-in-magento.

In this article we will use URL definition approach, therefore, we will add one more field to the above database to save the URL.

        id     title description           url

So, URL of the post will be filled out.

First technique to rewrite URL

Use URL rewrite function of Magento, you can get more details at Catalog-> URL Rewrite Management.

Picture1

There you will find out Magento creates a module to save URL rewrite for the Category and Product. Magento also allows you to add URL rewrite by clicking “Add Url Rewrite” to add a custome URL rewrite with:

Target Path: be the URL of the post, eg. blog/index/view/id/1

Request Path: be URL rewrite you will insert, eg. how-to-rewrite-url-in-magento.html

Obviously we will not manually add this information to save URL rewrite. Instead we will utilize url_rewrite model of core module (Mage::getModel(‘core/url_rewrite’)) to save URL of Blog in core_url_rewrite table after saving blog data.

After you have saved a post in Blog, you use the following code to save the URL rewrite:

Mage::getModel('core/url_rewrite')
    ->setIsSystem(true)
    ->setIdPath('blog/index/view/id/'.$blogId)
    ->setTargetPath('blog/index/view/id/'.$blogId)
    ->setRequestPath($url)
    ->save();

Note: $blogId  is the id of blog after saved and $url is URL that you defined.

Should you be reminded, the above command is applied to new post, if you want to edit an existing post, you need to update this record.

Second technique to rewrite URL

Still take the Blog module and same data fields as mentioned above, you create posts in back-end including adequate data of title, description, url.

Go to config.xml (app/code/local/MGS/Blog/etc)

Within global tag:

<global>
…
</global>

Add the following code

<events>
    <controller_front_init_routers>
        <observers>
            <blog_custom_router>
                <class>MGS_Blog_Controller_Router</class>
                <method>initControllerRouters</method>
           </blog_custom_router>
        </observers>
    </controller_front_init_routers>
</events>

In the main folder of app/code/local/MGS/Blog module you will create another folder named Controller in which you then create a file named Router.php with below content:

<?php
class MGS_Blog_Controller_Router extends Mage_Core_Controller_Varien_Router_Abstract
{
 /**
 * Initialize Controller Router
 *
 * @param Varien_Event_Observer $observer
 */
 public function initControllerRouters($observer)
 {
     /* @var $front Mage_Core_Controller_Varien_Front */
     $front = $observer->getEvent()->getFront();
     $front->addRouter('blog', $this);
 }
/**
 * Validate and Match Cms Page and modify request
 *
 * @param Zend_Controller_Request_Http $request
 * @return bool
 */
 public function match(Zend_Controller_Request_Http $request)
 {
     if (!Mage::isInstalled()) {
         Mage::app()->getFrontController()->getResponse()
         ->setRedirect(Mage::getUrl('install'))
         ->sendResponse();
         exit;
     }
     $identifier = trim($request->getPathInfo(), '/');
     $condition = new Varien_Object(array(
         'identifier' => $identifier,
         'continue' => true
     ));
if ($condition->getRedirectUrl()) {
     Mage::app()->getFrontController()->getResponse()
     ->setRedirect($condition->getRedirectUrl())
     ->sendResponse();
     $request->setDispatched(true);
     return true;
 }
if (!$condition->getContinue()) {
    return false;
 }

 $collection = Mage::getModel('blog/blog')
 ->getCollection();

 if(count($collection)>0){
     foreach($collection as $post){
         if($identifier == $post->getUrl()){
             $request->setModuleName('blog');
             $request->setControllerName('index');
             $request->setActionName('view');
             $request->setParam('id', $post->getId());
             return true;
         }
      }
    }
  }
}

The above piece of code means:
For example, when you type a path in a browser:
http://domain.com/how-to-rewrite-url-in-magento.

The function will compare the path: how-to-rewrite-url-in-magento.html with url in the data table of blog
If the path is similar to URL field of any record in the db then 4 command lines:

$request->setModuleName('blog');
$request->setControllerName('index');
$request->setActionName('view');
$request->setParam('id', $post->getId());

will help the system to understand that URL is corresponding to router: blog, controler: index, action: view and id is the id of the record having URL identical to the path in the browser.

Eg. Record having URL how-to-rewrite-url-in-magento.html and id 1, then:

http://domain.com/how-to-rewrite-url-in-magento.html

is corresponding to

http://domain.com/blog/index/view/id/1

Those are the two solutions we recommend to solve the URL friendly issue in Magento. We hope you find them helpful. We highly appreciate your comment and further contribution to the article.

Thanks a lot for your time!

Magesolution support team !

9537 Total Views 2 Views Today
  • http://smarttech.com Hyun

    wow… really good

    Thank you , it worked for me