Hey guys,

The URL Rewrite Management tool lets you change any URL that is associated with a product, category, or CMS page. When the redirect goes into effect, any existing links that point to the previous URL are automatically redirected to the new address. Follow us in this deep Magento Tutorial.

Lessons 30 consists of four sections:

  • Reason for using URL rewrite
  • Request flow in Magento
  • Request routing in Magento
  • How to rewrite URL in Magento

1. Reason for using URL rewrite

Magento is a web application implementing a Front Controller pattern, and this means that most HTTP requests are routed to the index.php file in the root folder. In order to display a category, a product, or a non-catalog information page, Magento parses the incoming URL to determine which modules and controllers must be engaged to process the request.

When the URL rewriting is not enabled Magento URLs look like this:

catalog/product/view/id/166 orcatalog/category/view/id/10

These are valid URLs and they contain important information, which Magento uses to produce HTML output. Thus, catalog points to the module Mage_Catalogthe product is translated into ProductControlerview – into viewAction, and the parameter id passes its value “10”. Altogether such URL generates a call to function

Mage_Catalog_ProductContoller::viewAction(), which renders a details page for a product with ID 10.

Despite being logical and well fit for an MVC web application which is Magento, this URL pattern has two significant drawbacks. First, it is not human-friendly. The IDs used in these URLs tell users nothing about the shop products or categories. Second, these URLs do not search engine optimized because they contain only generic terms (“catalog”, “product”, “category”) that have little effect in achieving high search engine positions. Ranking algorithms of the modern search engines (Google, above all) place high value into terms contained within URLs.

For these two reasons, human and search engine compatibility, it is imperative to include product and category names into shop URLs. Descriptive URLs consisting of words meant for both humans and search engines improve user experience and place the links to your shop higher in the search results relevant to your business.

Magento uses a rewrite engine to match descriptive URLs to its resources. The rewrite engine is a part of Magento core system and is responsible for matching incoming descriptive URLs to controllers, actions, and entity IDs. It is also tasked with the automated creation of descriptive URLs for Magento resources.

2. Request flow in Magento

magento request flow

  • Request URL
  • index.php (Mage::run())
  • app/Mage.php (Mage::app()->run())
  • app/code/core/Mage/Core/Model/App.php
    •  Install module database (Mage_Core_Model_Resource_Setup::applyAllDataUpdates())
    • Init and Dispatch controller ($this->getFrontController()->dispatch());
  • app/code/core/Mage/Core/Controller/Varien/Front.php
    • Chose router match for dispatch ($router->match($this->getRequest()))
  • app/code/core/Mage/Core/Controller/Varien/Router/Admin.php

app/code/core/Mage/Core/Controller/Varien/Router/Standard.php

app/code/core/Mage/Core/Controller/Varien/Router/Default.php

    • dispatch Action ($controllerInstance->dispatch($action);)
  • app/code/core/Mage/Core/Controller/Varien/Action.php
    • Call Action function (Example: indexAction())
  • custom Controller/Action
  • (app/code/core/Mage/Core/Controller/Response/Http.php)

3. Request routing in Magento

  • Init router before using: Mage_Core_Controller_Varien_Front::init()
    • Init Router uses configuration file with configuration path: default/web/routers

URL rewrite Magento

    • Init the custom router by event controller_front_init_before, controller_front_init_routers
    • Init the default router
  • Try to select router: Mage_Core_Controller_Varien_Front::dispatch()

request routing

    • Function match() of router will chose match controller/action to call. ($controllerInstance->dispatch($action);)
      • Predispatch
      • Call Controller Action Method
      • Postdispatch
    • Router will try to select router maximum – 100 times.
  • Dispatch to controller/action (Example: indexAction())

4. How to rewrite URL in Magento 1

4.1. Create URL rewrite manually

URL rewrite access

Login to Admin of Magento and click Catalog menu > URL Rewrite Management

add URL rewrite management

Click on button “Add URL Rewrite” to create a new URL rewrite

URL rewrite custom

Choose URL rewrite for category, product or custom.

URL rewrite Information path

    • Type this is Custom by defauult.
    • ID Path serves as an identifier to the rewrite entry and is unique within a store. Its value is comprised of ‘category’ or ‘product’ and the ID of the current category or product, e.g. “category/10” or “product/99”. Products can have multiple rewrites, each per category it is assigned to; and in such cases, id_path can be extended with a category id, e.g. “product/99/10”. The id_path property plays a part when a category or a product URL is created – the system generates an id_path and looks into the rewrite table for a matching entry, fetches the request_path and produces a URL.
    • Target Path – this property looks like a non-descriptive URL we discussed above. It contains references to the module, controller, action, and entity ID. When dispatching a request, Magento uses the Request Path extracted from the request URL to match to a Target Path. The matched entry will be used to pass the request to the proper controller action which will render the output.
    • Request Path is a descriptive URL slug generated from the entity’s urlkeyattribute. A Request Path of a category contains the urlkey of the parent categories, e.g.: furniture/living-room.html for the “living-room” category. Note the ”.html” suffix, which you can control with the configuration settings. For products, Magento generates multiple entries with different Request Path. First, a rewrite with a simple Request Path consisting only of the urlkey of the product itself, like ottoman.html. Then for every parent directory, a category path is added, e.g. furniture/living-room/ottoman.html. The Request Path property of sub-categories includes a complete path, e.g. furniture/living-room.html.
    • Redirect: It’s best to choose Permanent (301). It’s good for SEO aspect.
    • Description: Just an additional note for remembering what’s your purpose of rewrite!
  • store_id – in a multistore environment there can be multiple rewrites for the same category or product reflecting their possibly different names (internationalization) or category membership.
  • is_system – this property indicates that the rewrite has been created by the system automatically and can be modified when URL rewrites re-indexing starts. Permanent redirects created automatically by the shop when a product or a category urlkey is changed are set to non-system (i.e. is_system = 0) so that they can’t be affected by the URL re-indexing.
  • options contain a redirect code for the redirect rewrites. Regular URL rewrite entries have nothing in this property – they do not make web clients redirect. But as we have mentioned above, Magento can create redirect rewrites when necessary. These entries will have “PR” (“permanent redirect”) code saved on this property. Shop admins can create custom rewrites and provide redirect options for them. Custom rewrites can be temporary redirects, their options property will have “R” (“redirect”). We will discuss redirect options in details further below.

After filling in all fields, click “Save” to create a new URL rewrite.

4.2. Rewrite controller

For example: Rewrite controller checkout/cart in module Checkout

Code: app\code\local\Magestore\Lesson30\etc\config.xml

Step 1: Add configure in config.xml file

  • Method 1: insert config rewrite into tag global file config.xml
01 <global>
02
03 <rewrite>
04 <lesson30_checkout_cart>
05 <from><![CDATA[#^/checkout/cart/#]]></from>
06 <to>/lesson30/checkout_cart/</to>
07 </lesson30_checkout_cart>
08 </rewrite>
09 ...
10 </global>

from: expression to controller link

to: controller to rewrite

  • Method 2: Insert config routers into tag frontend file config.xml
01 <frontend>
02
03 <routers>
04 <checkout>
05 <args>
06 <modules>
07 <Magestore_Lesson30 before="Mage_Checkout">Magestore_Lesson30</Magestore_Lesson30>
08 </modules>
09 </args>
10 </checkout>
11 </routers>
12 ...
13 </frontend>
  • Method 3: Insert config router into tag global to rewrite all actions or one action of controller

Rewrite all action: rewrite all actions in controller

01 <global>
02
03 <routers>
04 <checkout>
05 <rewrite>
06 <cart>
07 <to>lesson30/cart</to>
08 </cart>
09 </rewrite>
10 </checkout>
11 </routers>
12 ...
13 </global>

Rewrite each action: Rewrite an identified action in controller

01 <global>
02
03 <routers>
04 <checkout>
05 <rewrite>
06 <cart>
07 <actions>
08 <index>
09 <to>lesson30/cart/index</to>
10 </index>
11 </actions>
12 </cart>
13 </rewrite>
14 </checkout>
15 </routers>
16 ...
17 </global>

Step 2: Write controller file

In this step, we need to write a controller (from controller rewrited), then rewrite actions we want.

Code: app\code\local\Magestore\Lesson30\controllers\CartController.php 

01 <?php
02
03 /**
04 * Magestore
05 *
06 * Online Magento Course
07 *
08 */
09
10 /**
11 * Lesson30 Index Controller
12 *
13 * @category Magestore
14 * @package Magestore_Lesson30
15 * @author Magestore Developer
16 */
17 require_once 'Mage/Checkout/controllers/CartController.php';
18 class Magestore_Lesson30_CartController extends Mage_Checkout_CartController
19 {
20 public function indexAction() {
21 # Just to make sure
22 error_log('Yes, I did it!');
23 parent::indexAction();
24 }
25 }

An important key to note is that Magento does not autoload controllers like it does with blocks and models. So, we’ll need to use “require_once” the file of the controller that we want to override.

UPDATE

5. How to Rewrite URL in Magento 2

You’ll find it easy on Magento 2 URL Rewrite when you’re completing for Magento 1 before. Just follow these simple steps:

Log in to Magento 2 backend then go through the path: Marketing > SEO & Search > URL Rewrites

Find the button Add URL Rewrite and click!

Then select type of URL you want to rewrite. You will see four types: Products, Categories, CMS Pages, Custom URLs

If not a Custom URL, you need to do an extra step: select a specific path for Category, Product or CMS Page then an Information Page just like in Magento 1 will appear (You’ll feel everything familiar on this step If you’ve done this on Magento 1!)

url-rewrite-m2

That’s it!

There is also a guide on how to configure URL rewrites on Magento 2, check it out!

This is the end of lesson 30: Magento URL rewrite in Magento Open Course. Thank you for reading. Don’t forget to keep up with our Magento Tutorial.

Source: URL Rewrite in Magento – Magento Open Course lesson 30