【发布时间】:2016-01-21 12:10:44
【问题描述】:
我想重定向这个网址http://www.businessbid.ae/stagging/web/feedback
到http://www.businessbid.ae。我能做什么?
【问题讨论】:
-
我建议不要这样做,最好显示一个有意义的错误消息并发送 HTTP 404,而不是仅仅重定向到主页,这可能会让用户感到困惑期待内容或消息,解释为什么他们无法获取内容
我想重定向这个网址http://www.businessbid.ae/stagging/web/feedback
到http://www.businessbid.ae。我能做什么?
【问题讨论】:
您应该创建一个侦听器来侦听onKernelExceptionEvent。
您可以检查 404 状态代码并从中设置重定向响应。
AppBundle\EventListener\Redirect404ToHomepageListener
namespace AppBundle\EventListener;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Symfony\Component\Routing\RouterInterface;
class Redirect404ToHomepageListener
{
/**
* @var RouterInterface
*/
private $router;
/**
* @var RouterInterface $router
*/
public function __construct(RouterInterface $router)
{
$this->router = $router;
}
/**
* @var GetResponseForExceptionEvent $event
* @return null
*/
public function onKernelException(GetResponseForExceptionEvent $event)
{
// If not a HttpNotFoundException ignore
if (!$event->getException() instanceof NotFoundHttpException) {
return;
}
// Create redirect response with url for the home page
$response = new RedirectResponse($this->router->generate('home_page'));
// Set the response to be processed
$event->setResponse($response);
}
}
services.yml
services:
app.listener.redirect_404_to_homepage:
class: AppBundle\EventListener\Redirect404ToHomepageListener
arguments:
- "@router"
tags:
- { name: kernel.event_listener, event: kernel.exception, method: onKernelException }
【讨论】:
NotFoundHttpException 是在没有匹配请求路径的路由时生成的。简而言之,是的。
app/console debug:event-dispatcher kernel.exception 中)?
您需要覆盖默认的Exception Controller。恕我直言,更好的解决方案是在 .htaccess 或 nginx 配置中完成这项工作。
【讨论】:
在你的控制器中试试这个:
$this->redirect($this->generateUrl('route_name')));
【讨论】: