我使用的是symfony2的404机制,大部分都可以使用。
这是一个场景。假设你去www.site.tld / whatever - 哪里/什么不存在。转到页面后,URL仍然是www.site.tld / whatever - 但框架返回了404页面。
如何将每个404强制到一个公共路径,例如www.site.tld / not-found,以便原始请求的路由不会保留在URL BAR中?
答案 0 :(得分:3)
接受的答案看起来有点像hacky虽然它显然有效,但它看起来似乎会提供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 }
答案 1 :(得分:2)
我用它来重定向所有不存在的路线:
anything:
path: /{mypath}
defaults:
_controller: FrameworkBundle:Redirect:urlRedirect
path: / #change this to whatever path
permanent: true
requirements:
mypath: ".+"
在所有现有的申请途径之后,我把它放在最底层。