I my project I would like to have a default route or controller that handles any request that does not match any available route. For example on requesting /abcd it now returns 404 as there is route defined for the path /abcd. I want any such request to be handle by a default controller that consider 'abcd' or any other string for that matter as a parameter. How can I implement that. If I define a route for path /{param} wouldn't that override other active routes
1 Answer
Go to /admin/config/system/site-information and set Default 404 (not found) page to the path of your custom controller.
In the controller place a typecasted $request
in the argument list. Then get the path from the request and either build a custom 404 response or redirect to another page:
use Symfony\Component\HttpFoundation\Request;
public function myController(Request $request) {
$path = $request->getPathInfo();
if ($path === '/abc') {
return ['#markup' => 'Path "abc" does not exist!'];
}
else {
return $this->redirect('<front>');
}
}
To answer the deleted comment. The controller can't set a status code 200, because it responds to a sub request and the master request is set to 404 no matter which 2xx status you set in the controller. For this you need an event subscriber: Does not redirect in EventSubscriber.