Search code examples
zend-frameworkhttp-redirecthttp-status-code-301

Zend Framework: How to 301 redirect old routes to new custom routes?


I have a large list of old routes that I need to redirect to new routes.

I am already defining my custom routes in the Bootstrap:

protected function _initRoutes()
{
    $router = Zend_Controller_Front::getInstance()->getRouter();

    $oldRoute = 'old/route.html';
    $newRoute = 'new/route/*';

    //how do I add a 301 redirect to the new route?

    $router->addRoute('new_route', 
        new Zend_Controller_Router_Route($newRoute,
            array('controller' =>'fancy', 'action' => 'route')
    ));
}

How can I add routes that redirect the old routes using a 301 redirect to the new routes?


Solution

  • Zend Framework does not have this type of functionality built in. So I have created a custom Route object in order to handle this:

    class Zend_Controller_Router_Route_Redirect extends Zend_Controller_Router_Route
    {
        public function match($path, $partial = false)
        {
            if ($route = parent::match($path, $partial)) {
                $helper = new Zend_Controller_Action_Helper_Redirector();
                $helper->setCode(301);
                $helper->gotoRoute($route);
            }
        }
    }
    

    Then you can use it when defining your routes:

    class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
    {
        protected function _initCustomRoutes()
        {
            $router = Zend_Controller_Front::getInstance()->getRouter();
            $route = new Zend_Controller_Router_Route_Redirect('old/route/*', array('controller'=>'content', 'action'=>'index'));       
            $router->addRoute('old_route', $route);
        }
    }