gpt4 book ai didi

php - 如何在 symfony 中将 404 重定向到主页?

转载 作者:可可西里 更新时间:2023-10-31 22:10:19 26 4
gpt4 key购买 nike

我想重定向这个 url http://www.businessbid.ae/stagging/web/feedbackhttp://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);
}
}

服务.yml

services:
app.listener.redirect_404_to_homepage:
class: AppBundle\EventListener\Redirect404ToHomepageListener
arguments:
- "@router"
tags:
- { name: kernel.event_listener, event: kernel.exception, method: onKernelException }

关于php - 如何在 symfony 中将 404 重定向到主页?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34923469/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com