So today I had to import a bunch of 301 redirects in Magento Enterprise. Needless to say, I’m saving this one for myself, but also for you: my fellow readers…
The method
The method to programmatically create (or import) 301 redirects into Magento Enterprise 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 |
/** * Import rule: * @param $fromUrl * @param $toUrl */ public function createRule($fromUrl, $toUrl) { // Create rewrite: /** @var Enterprise_UrlRewrite_Model_Redirect $rewrite */ $rewrite = Mage::getModel('enterprise_urlrewrite/redirect'); // Check for existing rewrites: foreach($this->storeIds as $storeId) { // Attempt loading it first, to prevent duplicates: $rewrite->loadByRequestPath($fromUrl, $storeId); $rewrite->setStoreId($storeId); $rewrite->setOptions('RP'); $rewrite->setIdentifier($fromUrl); $rewrite->setTargetPath($toUrl); $rewrite->setEntityType(Mage_Core_Model_Url_Rewrite::TYPE_CUSTOM); $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.
Magento Community
Looking for a way to import 301 redirects into Magento Community. Here’s how!
Visitors give this article an average rating of 3.9 out of 5.
How would you rate this article?
★ ★ ★ ★ ★
Where does this code go? And is it possible to add like a “Master rewrite” rule that first checked a database field for each product that would contain the “fromURL” and, if a match, redirect to the “toUrl”
So basically, programmatically checking the database for the URLs.
Obviously, this is to solve an “ecommerce redevelopment” in which the fromUrl from the old site was junk and the toUrl in Magento is the cat’s meow 😉
Any help is appreciated!