将404页面重定向到主页Zend2

时间:2014-09-09 11:40:43

标签: url-rewriting zend-framework2

在zend 2中,当控制器操作中没有url匹配时,它会将其发送到404页面。

现在我希望所有404都重定向到主页。下面是module.config.php文件中的代码。

不知道在调用任何404网址时会自动调用任何操作的位置。

'view_manager' => array(
    'display_not_found_reason' => true,
    'display_exceptions'       => true,
    'doctype'                  => 'HTML5',
    'not_found_template'       => 'error/404',
    'exception_template'       => 'error/index',
    'template_map' => array(
        'application/layout'           => __DIR__ . '/../view/layout/layout.phtml',
        'application/index/index'     => __DIR__ .     '/../view/application/index/index.phtml',
        'error/404'               => __DIR__ . '/../view/error/404.phtml',
        'error/index'             => __DIR__ . '/../view/error/index.phtml',
    ),

1 个答案:

答案 0 :(得分:2)

一个简单的事件监听器,具有高优先级的监听,应该足够了。

没有经过任何测试,但它应该让你知道如何拦截错误。

// Module.php
public function onBootstrap(MvcEvent $event)
{
    $application = $event->getApplication();
    $eventManager = $application->getEventManager();

    $eventManager->attach(MvcEvent::EVENT_DISPATCH_ERROR, function($e) {
        $error = $e->getError();
        switch ($error) {
            case Application::ERROR_CONTROLLER_NOT_FOUND:
            case Application::ERROR_CONTROLLER_INVALID:
            case Application::ERROR_ROUTER_NO_MATCH:

                $response = $event->getResponse();
                $response->getHeaders()->addHeaderLine('Location', '/home');
                $response->setStatusCode(302);

                return $response;
            break;
        }
    }, 100);
} 

我还建议您仔细查看Zend\Mvc\View\Http\RouteNotFoundStrategy中的代码,因为这是呈现404模板的'默认'侦听器。以上是早期做同样的事情而不是呈现视图模型它只返回响应(带有重定向)。

相关问题