3

How can I programmatically perform a 301 redirect in Magento?

12

In Mage_Core_Controller_Response_Http::setRedirect(), the second option allows you supply the redirect code (defaults to 302), so

Mage::app()->getResponse()
    ->setRedirect($someUrl, 301)
    ->sendResponse();
2

You can throw an exception in the predispatch event:

// https://github.com/magento-hackathon/HoneySpam/blob/master/app/code/community/Hackathon/HoneySpam/Model/Observer.php
$e = new Mage_Core_Controller_Varien_Exception();
$e->prepareForward('index','error','honeyspam');
throw $e;
1

If you want to redirect from within a controller, you can use the response object which is on the controller

class Some_Controller extends Mage_Core_Controller_Front_Action
{
    public function exampleAction()
    {
        $this->getResponse()->setRedirect('redirect-url.html', 301);
    }
0

If you need to redirect all URLs that are redirected by Magento with the default code 302 you can create an Observer in your own module for the dispatched event controller_response_redirect in Mage_Core_Controller_Response_Http::setRedirect():

public function forceDefaultRedirectCode($eventObject)
{
    $urlRedirectionCode = $eventObject->getTransport()->getCode();
    if ($urlRedirectionCode != '302') {
        return;
    }
    $eventObject->getTransport()->setCode(301);
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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