Simple route for year in blog url

Hi,

I’m trying to add year to blog posts, so:
/blog/slug
will become:
/blog/2021/slug

I’ve added to my config:

  'routes' => [
      [
        'pattern' => 'blog/(:num)/(:any)',
        'action'  => function ($slug) {

          return page('blog/' . $slug);
        }
      ]
    ],

and in my blog template my links to individual items look like this:

<a href="blog/<?= $item->date()->toDate('Y') ?>/<?= $item->slug() ?>">

This creates the proper urls but my error page is served instead of the blog-item template. Could somebody tell me what I’m missing? Thanks!

You are using two placeholders, so you need two variables, otherwise, $slug refers to the year, so should be

function($year, $slug)

Ok, thank you that works now.

Meanwhile I found:

In that thread there are two routes used, while one route seem to work I don’t understand why a second one might be necessary, can you explain?

The second route would redirect from the original url to the desired url so as to prevent duplicate URLs or to prevent errors in case the original URL is used anywhere.

Hmmm, confused, how does the first one work? What does it not do?
I don’t expect blog items with exactly the same url … same slug in the same year.

The route you added above returns the page with the given slug when for example blog/2022/my-first-article is called.

The second route would listen to the standard $article->url() URL, e.g blog/my-first-article and redirect it to your target URL with the year.

Don’t really understand this question…

But the first route does not imply that the original URL is not accessible anymore. Or to put it differently: Without the second route that redirects to the target URL, the post would still be accessible under blog/my-first-article.

:smile: What does it not do > so a second route is required

But the first route does not imply that the original URL is not accessible anymore. Without the second route that redirects to the target URL, the post would still be accessible under blog/my-first-article

Aha! Great that was my lightbulb moment.