Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 567
Andrew Avatar asked Nov 19 '10 20:11

Andrew


3 Answers

I've done it like this

  1. Add a Zend_Route_Regexp route as the old route
  2. Add Controller and action for the old route
  3. Add logic to parse old route
  4. Add $this->_redirect($url, array('code' => 301)) for this logic
like image 150
Vadyus Avatar answered Sep 29 '22 13:09

Vadyus


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);
    }
}
like image 24
Andrew Avatar answered Sep 29 '22 12:09

Andrew


In controller, try this way:

     $this->getHelper('redirector')->setCode(301);
     $this->_redirect(...);
like image 45
Krzysztof Cuber Avatar answered Sep 29 '22 11:09

Krzysztof Cuber