Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I redirect 404 to home in symfony?

Tags:

php

symfony

I want to redirect this url http://www.businessbid.ae/stagging/web/feedback to http://www.businessbid.ae. What can I do?

like image 467
Varun Sharma Avatar asked Jan 21 '16 12:01

Varun Sharma


People also ask

Should I redirect all 404 to homepage?

404s should not always be redirected. 404s should not be redirected globally to the home page. 404s should only be redirected to a category or parent page if that's the most relevant user experience available. It's okay to serve a 404 when the page doesn't exist anymore (crazy, I know).

How do I redirect 404 to 301?

Installing the plugin – Simple Alternatively, download the plugin and upload the contents of 404-to-301. zip to your plugins directory, which usually is /wp-content/plugins/ . Go to 404 to 301 tab on your admin menus. Configure the plugin options with available settings.


2 Answers

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 }
like image 100
qooplmao Avatar answered Sep 30 '22 01:09

qooplmao


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

like image 24
jkucharovic Avatar answered Sep 30 '22 03:09

jkucharovic