Zend Framework: How to 301 redirect old routes to new custom routes?
12,786
Solution 1
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);
}
}
Solution 2
I've done it like this
- Add a Zend_Route_Regexp route as the old route
- Add Controller and action for the old route
- Add logic to parse old route
- Add
$this->_redirect($url, array('code' => 301))
for this logic
Solution 3
In controller, try this way:
$this->getHelper('redirector')->setCode(301);
$this->_redirect(...);
Author by
Mike
Updated on June 08, 2022Comments
-
Mike almost 2 years
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?
-
Mike over 13 yearsI think that's what I'll do. Thanks!