Route to redirect to error page (404) on multilanguage site

Hi there,

On my multilanguage website, when someone is visiting a page which isn’t published or doesn’t exist, I would like to redirect to the error page with the right translation using a route (so URL becomes /404 or /en/404). I’ve tried the following code but it doesn’t work…

Does someone know how to do this properly please? :thinking:

[
  'pattern' => '(:any)',
  'language' => '*',
  'action' => function ($language, $uid) {
    $page = page($uid);
    if(!$page->isPublished() || !$page->exists()) go('error');
  }
],

See: Routes | Kirby CMS, the important part is site()->visit(), go() doesn’t have an option to pass a language code.

Using visit or go leads me to the same following error when I type a random page URL in the address bar, so I may have missed something…

Call to a member function isPublished() on null

Well, you don’t check for a page object before calling isPublished() if you have a page object. the same is true for exists()

So you would need:

  $page = page($uid);
    if(!$page || !$page->isPublished()) go('error');

Also note that the (:any) placeholder only catches first level pages.

Thanks for your help Sonja :slight_smile:
I’ve got this right now…

[
  'pattern' => '(:any)',
  'language' => '*',
  'action' => function ($language, $uid) {
    $page = page($uid);
    if(!$page || !$page->isPublished()) go('error');
    else return site()->visit($page, $language);
  }
]

… however I cannot preview the draft pages when logged in anymore. Is there any workaround using something like !kirby()->user() ?

I’m wondering what you are trying to achieve here? On a multi-language site, don’t you automatically get the correct error page when a page doesn’t exist? at least that should be the case…

But yes, you can of course check if a user is logged in

if (!$page || (!kirby->user() && $page->isPublished()) { 
// do stuff
}

I’m using the Swup JS library to play with the history API and I need error pages to redirect to a specific URL in order to animate correctly transitions, so this is very specific. I’ll try to find an alternative and will share here the solution.

Thanks for your time Sonja :wink: