Score:1

How can I customize the 403 page for specific routes?

br flag

On a D9 site, with an existing custom 403 page twig. I've been requested to show a different, variable, message from the "standard one" for a couple of specific routes.

I've tried with theme_preprocess_page__403(&$variables) but I couldn't determine the original route.

E.g. using \Drupal::routeMatch()->getRouteName() I got system.403 instead of the route name I need to check. I've checked solutions to find the refer route but none of them seemed to work.

Actually the two routes that need this specific 403 are created programmatically with a *routing.yml and relative controller in a custom module.

I wonder if it is possible somehow to specify the redirect path if the route requirements fails. I didn't find any documentation about, but that would another way to implements this requirement.

Score:5
cn flag

The 403 error page is not a redirect, so there is no referer. It's rendered in a sub-request which by default is using the route system.403.

From inside of the sub-request you can get the route name of the original request with

\Drupal::routeMatch()->getMasterRouteMatch()->getRouteName()
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.