如何将所有404错误重定向到公共路由


How to redirect all 404 errors to common route?

我使用的是symfony2的404机制,它基本上可以正常工作。

这是一个场景。假设你去www.site.tld/whatever -那里/什么不存在。进入页面后,URL仍然是www.site.tld/whatever,但是框架返回404页面。

我怎么能强制每个404到一个共同的路由,如www.site.tld/not-found,使原始请求的路由不留在URL栏?

这个公认的答案似乎有点黑客,尽管它显然有效,尽管它看起来会给出301状态码而不是404。

另一种方法是使用事件侦听器侦听NotFoundHttpException,如…

use Symfony'Component'HttpFoundation'RedirectResponse;
use Symfony'Component'HttpFoundation'Response;
use Symfony'Component'HttpKernel'Event'GetResponseForExceptionEvent;
use Symfony'Component'HttpKernel'Exception'NotFoundHttpException;
use Symfony'Component'Routing'Generator'UrlGeneratorInterface;
class NotFound404Listener
{
    protected $router;
    public function __construct(UrlGeneratorInterface $router)
    {
        $this->router = $router;
    }
    public function onKernelException(GetResponseForExceptionEvent $event)
    {
        if ($event->getException() instanceof NotFoundHttpException) {
            $url = $this->router->generateUrl(/** your route **/);
            $response = new RedirectResponse($url, 404);
            // Set redirect response to url of route with a 404 header
            $event->setResponse($response);
        }
    }
}

与服务(YAML)..

not.found.404.listener:
    class: %not.found.404.listsner.class%
    arguments:
        - @router
    tags:
        - { name: kernel.event_listener, event: kernel.exception, 
                                            method: onKernelException }

我用它来重定向所有不存在的路由:

anything:
    path:     /{mypath}
    defaults:
        _controller: FrameworkBundle:Redirect:urlRedirect
        path: / #change this to whatever path
        permanent: true
    requirements:
        mypath: ".+"

我把它放在所有现有应用程序路由之后的最底部