Search code examples
phproutesyamlsymfony

Catch-all route in Symfony 3


I have a catch-all fallback route in Symfony2 that I couldn't get to work in Symfony3. I tried this exact syntax (a verbatim copy of my Symfony2 route) and that didn't work.

fallback:
    path:     /{req}
    defaults: { _controller: MyBundle:Default:catchAll }
    requirements:
        req: ".+"

How can I get this working in Symfony3? (It's literally the only thing holding me back from using Symfony3 and keeping me at v2.8)


Solution

  • I found the current accepted answer almost useful for Symfony 4, so I'm going to add my solution:


    This is what I did to get it working in Symfony 4+:

    • Open /src/Controller/DefaultController.php, make sure there is a function called index(){}

      • It's not required to add the Request $request as first param as some comment suggest.
      • This is the method that will handle all urls caught by the routes.yaml
    • Open /config/routes.yaml, add this:

        yourRouteNameHere:
          path: /{req}
          defaults: { _controller: 'App\Controller\DefaultController::index' }
          requirements: #            the controller --^     the method --^
            req: ".*"`  # not ".+"