Route all suburls to top level page

Silverstripe Version: 4.7

Question:

I’m using javascript routing via the history api for a section of my website.
I would like to set up Silverstripe routing so that all of the sub urls of a particular page route to the top level page, so that the javascript can handle the routing from there, i.e.:

/products/category  
/products/category/subcategory

should both route (not redirect, I want the urls to stay the same) to

/products

which is the products page

I’ve tried many different combinations in routes.yml, PageController & ProductsPageController but nothing seems to work

You should be able to do it with the $url_handlers parameters in the controller:

<?php
class ProductPageController extends \SilverStripe\Control\Controller
{
    private static $url_handlers = [
        'products/$*' => 'index',
    ];

    public function index($request)
    {
        return $this->render();
    }
}

If that’s not what you’re after, let us know what you’ve already tried and someone might be able to help a bit further. If your controller is already at the right level in the URL structure, you could try:

  private static $url_handlers = [
        '$*' => 'index',
    ];

Don’t forget to dev/build?flush when you make those changes :wink:

In the end the problem was that the ProductsPage was not picking up the ProductsPageController. I added a $controller_name property to ProductsPage, as well as your code, and everything worked!

Thank you

1 Like