How can I programmatically perform a 301 redirect in Magento?

up vote 11 down vote accepted

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();

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;

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);
    }

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 acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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