Custom routes interfering with JSON routes

Hello!

I have a website which follows this structure:

– Home
– Articles
    – Category A
        – Article 1
        – Article 2
        – Article 3
    – Category B
        – Article 1
        – Article 2
        – Article 3
    – Category C
        – Article 1
        – Article 2
        – Article 3

I have implemented in some parts of the site a loading more button following this tutorial.

The url when I go to an article looks like this: “websitename.com/articles/category-name/article-name” and I have been trying to make some routes to remove the “/articles” part. And it works I can have this url “websitename.com/category-name/article-name” working.

The problem is the load more links don’t work anymore. It seems the custom routes are interfering with the json urls.

Here are the routes:

[
      'pattern' => '(:any)',
      'action'  => function ($any) {
        if ($categoryPage = page('articles')->children()->findBy('slug', $any)) {
          return ($categoryPage);
        }
        
        // Try to find a page with this slug anywhere in the site
        if ($page = site()->find($any)) {
          return $page;
        }

        // Let Kirby show the 404
        return site()->errorPage();
      }
    ],
    [
      'pattern' => '(:any)/(:any)',
      'action'  => function ($category, $article) {
        if ($articlePage = page('articles')->children()->findBy('slug', $category)->children()->findBy('slug', $article)) {
          return ($articlePage);
        }

        // Try to find a page with this slug anywhere in the site
        if ($page = site()->find($article)) {
          return $page;
        }

        // Let Kirby show the 404
        return site()->errorPage();
      }
    ]

Is there a possibility to omit the json routes in these patterns?

Thank you!

Yes, you are free to use any route patterns that fit your use case, you are not limited to the named placeholders like (:any) and all, but can use regex patterns of your choice, see docs: Routes | Kirby CMS. Using (:alphanum) instead of (:any) for example, would exclude routes with a dot.