Redirect for pages that have been moved to a different folder


#1

Hello.

I am trying to wrap my mind around a specific redirect scenario.

Suppose we have two folders, one named “blog” and another named “calendar”.

Page “blog/post-1” was move to the “calendar” folder so it’s now “calendar/post-1”, therefore “blog/post-1” will give a 404 error.

What i want is to check if a page under “blog” exists and if it does not, look for it under “calendar”.

If the page is found under calendar then the user should be redirected to it.

Any ideas of how this could be done?

Thanks in advance.


#2

You can do this with a route: https://getkirby.com/docs/developer-guide/advanced/routing

c::set('routes', [
  [
    'pattern' => 'blog/(:any)',
    'action'  => function($uid) {
      $page = page('blog/'.$uid);

      if(!$page) $page = page('calendar/' . $uid);
      if(!$page) $page = site()->errorPage();

      return site()->visit($page);
    }
  ]
]);

#3

Thanks a lot! This works out of the box. However, although it redirects to the correct page, the url remains “blog/post-1” instead of “calendar/post-1”.


#4

Yes, true, try this instead:

c::set('routes', [
  [
    'pattern' => 'blog/(:any)',
    'action'  => function($uid) {
      if($page = page('blog/'.$uid)) {
           return site()->visit($page);
      } elseif($page = page('calendar/' . $uid)) {
            go($page->url());
      } else {
           go('error');
      } 
    }
  ]
]);

#5

Perfect! Thank you so much!