How can I make a dynamic canonical tag on Magento's internal search?

1.6k views Asked by At

When I do a internal search in magento (i.e search for a product) and after that try to filter the results (filter by price), some querystrings are added to my URL, but Google point's out like a duplicated content.

Magento have the canonical tag feature on categories and product's, but I couldnt find it in "search" queries and filters.

My question is: How can i add canonical tags on magento's search when I filter the results?

2

There are 2 answers

0
Mageworx On

We generally recommend to hide internal site search from getting indexed ( you can do that with the standard "NOINDEX, FOLLOW" tags).

But if for some reason you really need to index it, here is the simplest code that lets you add a canonical URL.

Please note that in this case we use the default search. In this code, the canonical URL contains only the search query, without any filters.

/app/design/frontend/{your_package}/{your_theme}/template/page/html/head.phtml

Add this code:

<?php

$controller = Mage::app()->getFrontController();
if(is_object($controller) && is_callable(array($controller, 'getAction'))){
    $action = $controller->getAction();
    if(is_object($action) && is_callable(array($action, 'getFullActionName'))){
        $fullActionName = $action->getFullActionName();        
    }
}

if(!empty($fullActionName) && $fullActionName == 'catalogsearch_result_index')
{
    $request = $this->getRequest();
    $params  = $request->getParams();

    if(!empty($params['q'])){
        $action = $request->getActionName();
        if($action == 'index'){
            $action = '';
        }
        $canonicalUrl = $this->getBaseUrl() . $request->getRouteName() .DS. $request->getControllerName() .DS. $action . '?q=' . $params['q'];
        echo "<link rel=\"canonical\" href=\"$canonicalUrl\" />";
        echo "<!--Canonical URL was added from template head.phtml-->";
    }
}

?>

Also note that we recommend to use the toolbar parameter limit=all. Without it, it'll be hard to get the right Canonical URL on the pages with pagination.

In case this parameter is turned on, (you can check it under System->Configuration->Catalog->Catalog->Frontend->Allow All Products per Page), you need to add 'limit=all' to the URL.

P.S. To learn more about the topic, please read this guide by Google: http://googlewebmastercentral.blogspot.com/2013/04/5-common-mistakes-with-relcanonical.html

0
Javier Carter On

You can avoiding crawler through robots.txt as well

User-agent: * Disallow: /catalogsearch/

above code will avoid search pages getting crawled in google.