简体   繁体   中英

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 . What can I do?

You should create a listener to listen for the onKernelExceptionEvent .
In that you can check for the 404 status code and set the redirect response from that.

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 }

You need to override default Exception Controller . IMHO better solution is to do that job in .htaccess or nginx config.

试试这个到你的控制器:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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