I already covered this topic before for Magento Enterprise, but of course: there are cases you need to import 301 redirects into Magento Community at some point. Here’s how to do this:
The method
The method to programmatically create (or import) 301 redirects into Magento Community is as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
/** * Import rule for Magento Community * @param $fromUrl * @param $toUrl */ public function createRuleCommunity($fromUrl, $toUrl) { // Create rewrite: /** @var Mage_Core_Model_Url_Rewrite $rewrite */ $rewrite = Mage::getModel('core/url_rewrite'); // 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(); } } |
Redirect to the homepage
If you need to redirect to the homepage, you can simply set the $toUrl to index.php or the URL identifier of your homepage. Setting it to / wont work. I bumped into this one because a lot of 301 redirects redirected to the homepage, since the product in question no longer existed on the new website.
Visitors give this article an average rating of 3.6 out of 5.
How would you rate this article?
★ ★ ★ ★ ★