I had a store with category path turned on for product urls. After realising that, it creates duplicate content issues in SEO, I turned it off.
Since product urls (with category path) are already linked in Social Media and Email Campaigns, Google Analytics tracking is showing lots of such visited urls.
Now I am trying to redirect the product with category path to the one having product url key only.
For example:
http://mystore.com/category/sub-category/product.html --> http://mystore.com/product.html
http://mystore.com/category/product.html --> http://mystore.com/product.html
I tried to use the following script which implements the event controller_action_predispatch
but it's not working as expected:
public function controllerActionPredispatch(Varien_Event_Observer $observer)
{
$action = $observer->getControllerAction();
$request = $action->getRequest();
$requestUrl = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : $request->getRequestUri();
$fullActionName = $action->getFullActionName();
$storeId = Mage::app()->getStore()->getId();
if (in_array($fullActionName, array('catalog_product_view'))) {
$product = Mage::registry('current_product');
$category = Mage::registry('current_category');
if ($product && $product->getId() && $category && $category->getId()) {
$categoryUrlKey = $this->getCategoryUrlKey($category->getId(), $storeId);
if (empty($categoryUrlKey)) {
$categoryUrlKey = $category->getUrlKey();
}
if (stripos($requestUrl, '/' . $categoryUrlKey . '/') !== false) {
$urlKey = $this->getProductUrlKey($product->getId(), $storeId);
if (empty($urlKey)) {
$urlKey = $product->getUrlKey();
}
$redirectUrl = Mage::getUrl() . trim($urlKey, '/') . '.html';
$action->getResponse()->setRedirect($redirectUrl, 301);
$action->getRequest()->setDispatched(true);
return;
}
}
}
}
public function getCategoryUrlKey($categoryId, $storeId = 0)
{
$resource = Mage::getSingleton('core/resource');
$connection = $resource->getConnection('core_read');
$sql = "select value from catalog_category_entity_url_key where entity_id = ? and store_id = ? limit 1";
$urlKey = $connection->fetchOne($sql, array($categoryId, $storeId));
return $urlKey;
}
public function getProductUrlKey($productId, $storeId = 0)
{
$resource = Mage::getSingleton('core/resource');
$connection = $resource->getConnection('core_read');
$sql = "select value from catalog_product_entity_url_key where entity_id = ? and store_id = ? limit 1";
$urlKey = $connection->fetchOne($sql, array($productId, $storeId));
return $urlKey;
}
Any idea for the perfect solution? I am using #Magento #EE version 1.13.
[Edit] One strange thing is
$action->getResponse()->setRedirect($redirectUrl, 301);
$action->getRequest()->setDispatched(true);
redirection doesn't work in live server but works in localhost.