Disable access to /home

Hello!
My blog posts are stored in the ‘home’ directory in subfolders by default. Now I want to forbid direct access to site.com/home or redirect it to the normal site.com. Which settings do I have to make here for routes?

Thank you.

What exactly do you want to achieve? You don’t want your subpages to be accessible at all, because they are only rendered on the home page without a link to a single page view?

In that case, you can use a route with a pattern home/(:any) that redirects to the site url. https://example.com/home redirects to https://example.com anyway.

No. I want the subpages to still be accessible, but not the parent folder. I have already created a route for the subpages.

config.php:

return [
    'debug' => true,
    'routes' => [
        [
            'pattern' => '(:any)',
            'action'  => function($uid) {
                $page = page($uid);
                if(!$page) $page = page('home/' . $uid);
                if(!$page) $page = site()->errorPage();
                return site()->visit($page);
            }
        ],
        [
            'pattern' => 'home/(:any)',
            'action'  => function($uid) {
                go($uid);
            }
        ]
    ]
];

And these routes prevent the usual automatic redirects from home to /?

Yes. blog.test/home does not redirect to blog.test.

Try:

 [
            'pattern' => '(:any)',
            'action'  => function($uid) {
                $page = page($uid);
                if ($page && $page->id() === 'home') {
                  $this->next();
                }
                if(!$page) $page = page('home/' . $uid);
                if(!$page) $page = site()->errorPage();
                return site()->visit($page);
            }
        ],

If that doesn’t work, I have to test myself…

Thank you for your quick answer, but now i get a Call to a member function id() on null error.

Let’s try with parenthesis around the $page variable…

if (($page ) && $page->id() === 'home') {

Seems to work…

Yes, this works perfect!
Thank you very much! :blush:

1 Like