如何将所有 404 错误重定向到公共路由? [英] How to redirect all 404 errors to common route?
问题描述
我正在使用 symfony2 的 404 机制,该机制基本正常.
I'm using symfony2's 404 mechanism, which mostly works okay.
这是一个场景.假设你去 www.site.tld/whatever - 那里/whatever 不存在.转到页面后,URL 仍然是 www.site.tld/whatever - 但框架会返回 404 页面.
Here's a scenario. Say you go to www.site.tld/whatever - where /whatever does not exist. After you go to the page, the URL remains www.site.tld/whatever - but a 404 page is returned by the framework.
如何强制每个 404 到一个公共路由,例如 www.site.tld/not-found,以便原始请求的路由不会保留在 URL BAR 中?
How can I force EVERY 404 to a common route, such as www.site.tld/not-found, so that the original requested route does NOT remain in the URL BAR?
推荐答案
尽管它显然有效,但已接受的答案似乎有点笨拙,尽管它看起来确实会给出 301 状态代码而不是 404.
The accepted answer to this seems a little hacky although it clearly works, although it does seem like it would give a 301 status code rather than a 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)..
with the service (YAML)..
not.found.404.listener:
class: %not.found.404.listsner.class%
arguments:
- @router
tags:
- { name: kernel.event_listener, event: kernel.exception,
method: onKernelException }
这篇关于如何将所有 404 错误重定向到公共路由?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!