[英]How can I redirect 404 to home in symfony?
我想將此網址http://www.businessbid.ae/stagging/web/feedback
重定向到http://www.businessbid.ae
。 我能做什么?
您應該創建一個偵聽器來偵聽onKernelExceptionEvent
。
在那里,您可以檢查404狀態代碼並從中設置重定向響應。
的appbundle \\事件監聽\\ 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 }
您需要覆蓋默認的異常控制器 。 恕我直言更好的解決方案是在.htaccess
或nginx配置中完成這項工作。
試試這個到你的控制器:
$this->redirect($this->generateUrl('route_name')));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.