You are on page 1of 7

Magento URL Rewrite Process

Magento, Nuts & Bolts Sep 2 nd, 2015 0 Comments


Magento URL Rewrite is core feature in magento and is used through. This is mainly used to generate SEO
friendly URL’s for products, categories, cms pages etc. Rewrite is also possible to do through config.xml file
when you create modules. We will see both of these in detail and how they work.

Database Table URL Rewrites


Magento stores URL rewrites in the table ‘core_url_rewrite’. It has the following columns
url_rewrite_id: primary key
store_id: store id for the rewrite is done
id_path: internal unique identifier used. its usally ‘product’ + product_od or ‘category’ + category_id etc
request_path: the url which is opened in browser
target_path: the which should open if request path is matched
is_system: if the rewrite is system generated or manually created
options: different redirect options like ‘RP’ which is permanent redirect (302 Redirect), ‘R’ which is a 301
Redirect, or null/empty
description: any description if entered
category_id: the category id if the redirect is for a cateogry
product_id : the product id if redirect is for a product

We can also add custom rewrites to this table from Admin -> Catalog -> Url Rewrite Management

DB Rewrite Implementation
Let’s see in detail how magento implement these rewrites when we open a URL in browser

When we open a URL in browser, the main control goes to


Mage_Core_Controller_Varien_Front::dispatch() where this code is written

1$this->_getRequestRewriteController()->rewrite();

This basically creates an object of class ‘core/url_rewrite_request’ and calls the rewrite function there.
This is what the rewrite() function looks like

1
public function rewrite()
2{
3     
4    if (!$this->_request->isStraight()) {
5        $this->_rewriteDb();
6    }
7    $this->_rewriteConfig();
    return true;
8}
9

\\\\\\ we can see here _rewriteDb() and _rewriteConfig() functions are called here which manage the db and
config rewrites respectively. Lets look at db rewrite first.

1 protected function _rewriteDb()


{
2     if (null === $this->_rewrite->getStoreId() || false === $this->_rewrite-
3 >getStoreId()) {
4
5         $this->_rewrite->setStoreId($this->_app->getStore()->getId());
    }
6
7  
    $requestCases = $this->_getRequestCases();
8     $this->_rewrite->loadByRequestPath($requestCases);
9  
1     $fromStore = $this->_request->getQuery('___from_store');
0     if (!$this->_rewrite->getId() && $fromStore) {
1         $stores = $this->_app->getStores(false, true);
        if (!empty($stores[$fromStore])) {
1             /** @var $store Mage_Core_Model_Store */
1             $store = $stores[$fromStore];
2             $fromStoreId = $store->getId();
1         } else {
3             return false;
        }
1
 
4         $this->_rewrite->setStoreId($fromStoreId)->loadByRequestPath($requestCases);
1         if (!$this->_rewrite->getId()) {
5             return false;
1         }
6  
        // Load rewrite by id_path
1         $currentStore = $this->_app->getStore();
7         $this->_rewrite->setStoreId($currentStore->getId())->loadByIdPath($this-
1 >_rewrite->getIdPath());
8  
1         $this->_setStoreCodeCookie($currentStore->getCode());
9  
2         $targetUrl = $currentStore->getBaseUrl() . $this->_rewrite->getRequestPath();
        $this->_sendRedirectHeaders($targetUrl, true);
0     }
2  
1     if (!$this->_rewrite->getId()) {
2         return false;
2     }
2  
3     $this->_request->setAlias(Mage_Core_Model_Url_Rewrite::REWRITE_REQUEST_PATH_ALIAS,
        $this->_rewrite->getRequestPath());
2     $this->_processRedirectOptions();
4  
2     return true;
5 }
2
6
2
7
2
8
2
9
3
0
3
1
3
2
3
3
3
4
3
5
3
6
3
7
3
8
3
9
4
0
4
1

The first thing which happens there is creating of request cases. Request cases is basically an array which has
difference combinations of the request URL priority wise. e.g if the input URL is
“http://yourmagento.com/abc.html?test=1”
The request cases which get generated are
1. abc.html?test=1
2. abc.html/?test=1
3. abc.html
4. abc.html/

similarly if the request url is “http://yourmagento.com/abc.html/?test=1” , request cases are


1. abc.html/?test=1
2. abc.html?test=1
3. abc.html/
4. abc.html

not the difference in slash order based on URL.


here is code for the same which magento uses

2 protected function _getRequestCases()


{
3
    $pathInfo = $this->_request->getPathInfo();
4     $requestPath = trim($pathInfo, '/');
5     $origSlash = (substr($pathInfo, -1) == '/') ? '/' : '';
6     // If there were final slash - add nothing to less priority paths. And vice versa.
7     $altSlash = $origSlash ? '' : '/';
8  
    $requestCases = array();
9     // Query params in request, matching "path + query" has more priority
1     $queryString = $this->_getQueryString();
0     if ($queryString) {
1         $requestCases[] = $requestPath . $origSlash . '?' . $queryString;
1         $requestCases[] = $requestPath . $altSlash . '?' . $queryString;
    }
1     $requestCases[] = $requestPath . $origSlash;
2     $requestCases[] = $requestPath . $altSlash;
1     return $requestCases;
3 }
1
4
1
5
1
6
1
7
1
8

Once request cases are generated, magento check’s database for matches using function

1$this->_rewrite->loadByRequestPath($requestCases);

This is defined the resource model ‘Mage_Core_Model_Resource_Url_Rewrite’

1 public function loadByRequestPath(Mage_Core_Model_Url_Rewrite $object, $path)


{
2
    if (!is_array($path)) {
3         $path = array($path);
4     }
5  
6     $pathBind = array();
7     foreach ($path as $key => $url) {
        $pathBind['path' . $key] = $url;
8     }
9     // Form select
1     $adapter = $this->_getReadAdapter();
0     $select  = $adapter->select()
1         ->from($this->getMainTable())
1         ->where('request_path IN (:' . implode(', :', array_flip($pathBind)) . ')')
        ->where('store_id IN(?)', array(Mage_Core_Model_App::ADMIN_STORE_ID, (int)
1 $object->getStoreId()));
2     $items = $adapter->fetchAll($select, $pathBind);
1  
3     // Go through all found records and choose one with lowest penalty - earlier path in
1 array, concrete store
    $mapPenalty = array_flip(array_values($path)); // we got mapping array(path =>
4
index), lower index - better
1     $currentPenalty = null;
5     $foundItem = null;
1     foreach ($items as $item) {
6         if (!array_key_exists($item['request_path'], $mapPenalty)) {
            continue;
1         }
7         $penalty = $mapPenalty[$item['request_path']] << 1 + ($item['store_id'] ? 0 : 1);
1         if (!$foundItem || $currentPenalty > $penalty) {
8             $foundItem = $item;
1             $currentPenalty = $penalty;
            if (!$currentPenalty) {
9                 break; // Found best matching item with zero penalty, no reason to
2 continue
0             }
2         }
    }
1
2  
    // Set data and finish loading
2
2
3
2
4
2
5
2
6
2
7
2
8
2
9
3
0
3
1
    if ($foundItem) {
3         $object->setData($foundItem);
2     }
3  
3     // Finish
3     $this->unserializeFields($object);
    $this->_afterLoad($object);
4
3  
    return $this;
5 }
3
6
3
7
3
8
3
9
4
0
4
1
4
2
4
3
4
4

What this code does it, create an sql query like

SELECT `core_url_rewrite`.* FROM `core_url_rewrite` WHERE (request_path IN (:path0,


1:path1)) AND (store_id IN(0, 1))

and bind it to an array like


1Array
2(
3    [path0] =>
4    [path1] =>
)
5

Next we have code which calculates penalty using bitwise operators, but what the code does in short is
return “earlier path in array and concrete store”.

So once we get the final request path, if any magento does the final redirect using

1$this->_processRedirectOptions();

In between there is other code as well, but its self explanatory.

So this is how database redirect options work, let see now how config redirect options work.

Another thing to see is when does magento create these url rewrites
This is done at ‘Mage_Catalog_Model_Indexer_Url’ using the “reindexAll()” function.

Configuration Based Rewrite


Here is the code for configuration based rewrites
protected function _rewriteConfig()
{
6
    $config = $this->_config->getNode('global/rewrite');
7     if (!$config) {
8         return false;
9     }
1     foreach ($config->children() as $rewrite) {
        $from = (string)$rewrite->from;
0         $to = (string)$rewrite->to;
1         if (empty($from) || empty($to)) {
1             continue;
1         }
2         $from = $this->_processRewriteUrl($from);
1         $to   = $this->_processRewriteUrl($to);
3  
        $pathInfo = preg_replace($from, $to, $this->_request->getPathInfo());
1         if (isset($rewrite->complete)) {
4             $this->_request->setPathInfo($pathInfo);
1         } else {
5             $this->_request->rewritePathInfo($pathInfo);
        }
1
    }
6     return true;
1 }
7 protected function _processRewriteUrl($url)
1 {
    $startPos = strpos($url, '{');
8     if ($startPos !== false) {
1         $endPos = strpos($url, '}');
9         $routeName = substr($url, $startPos + 1, $endPos - $startPos - 1);
2         $router = $this->_getRouterByRoute($routeName);
0         if ($router) {
            $frontName = $router->getFrontNameByRoute($routeName);
2             $url = str_replace('{' . $routeName . '}', $frontName, $url);
1         }
2
2
2
3
2
4
2
5
2
6
2
7
2
8     }
2     return $url;
9 }
3
0
3
1
3
2
3
3
3
4
3
5

This is xml which we write in our config.xml files

1<global>
    <rewrite>
2        <designer_url>
3            <from><![CDATA[#^/author/id/#]]></from>
4            <to><![CDATA[/designer/index/index/id/]]></to>
5            <complete>1</complete>
        </designer_url>
6    </rewrite>
7</global>

As we can see the code is quite self explanatory on how this works. One thing to note is magento uses
‘preg_replace’ to match url, so we can use regular expressions as well.

You might also like