Custom route and redirecting turns into infinite loop


I’m working on a website that has a calendar for events. I set up a custom route that gives me back the requested month like so:

  'routes' => [
      'pattern' => 'events/calendar/(:all)',
      'action' => function ($month) {
        $data = [
          'month' => $month,
        return page('events')->render($data);

This works well for the pattern that I use which is "y-m" => "23-04". But now I also want the events page to redirect automatically to current month. So when I go to /events it should take me to /events/calendar/23-04

  $currentMonth = date('y-m');

  $subpage = "/events/calendar/" . $currentMonth . "/";

  header('Location: ' . $subpage);

I tried it like that but I think it gives me an infinite loop, since chrome is telling me that localhost redicted me too many times:


How can I fix it? Also, if there is a better way to do this, please tell me.

Thank you for your help!


I actually just fixed it by checking if $month is NULL and only then redirect. This is probably not the cleanest but it works!

Not that the all placeholder could refer to anything after events/calendar, e.g. events/calendar/whatever/whatever/whatever. (:any)` would be the better option here.

Thank you @texnixe!

But I guess regex would be even more suitable, right? At the moment I can’t get it to work.
I have the following expression ^\d{2}-\d{2}$. It should work for all sorts of year-month combinations.

But this pattern doesn’t seem to work:

'pattern' => 'events/calendar/(^\d{2}-\d{2}$'),

What am I doing wrong here?

'pattern' => 'events/calendar/(\d{2}-\d{2})',

Your pattern will also match none-existing day/month combinations, though, like 45-27