简体   繁体   English

如何在symfony中将404重定向到home?

[英]How can I redirect 404 to home in symfony?

I want to redirect this url http://www.businessbid.ae/stagging/web/feedback to http://www.businessbid.ae . 我想将此网址http://www.businessbid.ae/stagging/web/feedback重定向到http://www.businessbid.ae What can I do? 我能做什么?

You should create a listener to listen for the onKernelExceptionEvent . 您应该创建一个侦听器来侦听onKernelExceptionEvent
In that you can check for the 404 status code and set the redirect response from that. 在那里,您可以检查404状态代码并从中设置重定向响应。

AppBundle\\EventListener\\Redirect404ToHomepageListener 的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.yml

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

You need to override default Exception Controller . 您需要覆盖默认的异常控制器 IMHO better solution is to do that job in .htaccess or nginx config. 恕我直言更好的解决方案是在.htaccess或nginx配置中完成这项工作。

试试这个到你的控制器:

$this->redirect($this->generateUrl('route_name')));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM