0

Well this might be duplicate of others but it didn't got my answer...

Okay so I want to redirect user from old product url to new product url so by googling I've found following code....

Here I'm passing following variables in createRuleCommunity function.

$fromUrl = 'http://www.example.com/product-old-url.html';
$toUrl   = 'http://www.example.com/product-new-url.html';

public function createRuleCommunity($fromUrl, $toUrl)
    {
        // Create rewrite:
        /** @var Mage_Core_Model_Url_Rewrite $rewrite */
        $rewrite = Mage::getModel('core/url_rewrite');
        $this->storeIds = Mage::app()->getStores();
        // Check for existing rewrites:
        foreach($this->storeIds as $storeId)
        {
            // Attempt loading it first, to prevent duplicates:
            $rewrite->loadByIdPath($fromUrl);

            $rewrite->setStoreId($storeId);
            $rewrite->setOptions('RP');
            $rewrite->setIdPath($fromUrl);
            $rewrite->setRequestPath($fromUrl);
            $rewrite->setIsSystem(0);
            $rewrite->setTargetPath($toUrl);

            $rewrite->save();
        }
    }

After executing this function when I visit

http://www.example.com/product-old-url.html

It's not direceting me to new url which is http://www.example.com/product-new-url.html

And new url (http://www.example.com/product-new-url.html) is become 404 Error

I want when user visit following url

http://www.example.com/product-old-url.html

He/She should be redirected to new url

http://www.example.com/product-new-url.html

So in short by any visiting old url user should be redirect to new product url.

So is there any direct way to do so??

All I've is product old url and new url and I want to do this job programmatically.

1 Answer 1

1

Anyways following has done the job..

    // get the new url
    $new_url = Mage::getModel('catalog/product_url')->formatUrlKey('new-product-url');

    // load the product object
    $_product =  Mage::getModel('catalog/product')->loadByAttribute('sku',$product['sku']);

    // save rewrites history for old to new url redirect
    $_product->setData('save_rewrites_history', true);

    // set new url
    $_product->setUrlKey($new_url);

    // set new url path
    $_product->setUrlPath($new_url);

    // save the product
    $_product->save();

After executing above script just reindex

Catalog URL Rewrites index

After that try to visit your old url and you will be redirected to the new url.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.