Sam Levin
Sam Levin

Reputation: 3416

How to redirect all 404 errors to common route?

I'm using symfony2's 404 mechanism, which mostly works okay.

Here's a scenario. Say you go to www.site.tld/whatever - where /whatever does not exist. After you go to the page, the URL remains www.site.tld/whatever - but a 404 page is returned by the framework.

How can I force EVERY 404 to a common route, such as www.site.tld/not-found, so that the original requested route does NOT remain in the URL BAR?

Upvotes: 1

Views: 722

Answers (2)

qooplmao
qooplmao

Reputation: 17759

The accepted answer to this seems a little hacky although it clearly works, although it does seem like it would give a 301 status code rather than a 404.

Another approach would be to use an event listener listening for a NotFoundHttpException like so..

use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;

class NotFound404Listener
{
    protected $router;

    public function __construct(UrlGeneratorInterface $router)
    {
        $this->router = $router;
    }

    public function onKernelException(GetResponseForExceptionEvent $event)
    {
        if ($event->getException() instanceof NotFoundHttpException) {
            $url = $this->router->generateUrl(/** your route **/);

            $response = new RedirectResponse($url, 404);
            // Set redirect response to url of route with a 404 header

            $event->setResponse($response);
        }
    }
}

with the service (YAML)..

not.found.404.listener:
    class: %not.found.404.listsner.class%
    arguments:
        - @router
    tags:
        - { name: kernel.event_listener, event: kernel.exception, 
                                            method: onKernelException }

Upvotes: 3

ihsan
ihsan

Reputation: 2289

I use this to redirect all non-existent route:

anything:
    path:     /{mypath}
    defaults:
        _controller: FrameworkBundle:Redirect:urlRedirect
        path: / #change this to whatever path
        permanent: true
    requirements:
        mypath: ".+"

I put it on the very bottom after all existing application route.

Upvotes: 2

Related Questions