Redirect 'Link to First Child' Pages

This is a community-contributed tutorial. This tutorial is over a year old and may not apply to your version of Concrete CMS.
May 9, 2016

On sites where the replace_link_with_first_in_nav attribute is used, it may be ideal to redirect a visitor to the correct page if they manually enter the parent page's URL. This can be achieved with an event listener in the application bootstrap.

Let's say you have the following tree

  • example.com/page-1 [replace_link_with_first_in_nav attribute is set on this page]
  • example.com/page-1/sub-page-1
  • example.com/page-1/sub-page-2

Typically all the navigation entries for /page-1 automatically point to /page-1/sub-page-1 however if the user types in /page-1 for some reason they will see whatever content has been added there (which probably isn't any).

By adding the following snippet to your /application/bootstrap/app.php they will automatically be redirected to the first child page with a 301 response.

use Concrete\Core\Routing\Redirect;

Events::addListener('on_page_view', function($event) {
    $page = $event->getPageObject();
    if ($page->getCollectionAttributeValue('replace_link_with_first_in_nav')) {
        $sub = $page->getFirstChild();
        if (is_object($sub)) {
            Redirect::page($sub, 301)->send();
        }
    }
});
Recent Tutorials
How to Automate the Copyright Year
Dec 27, 2024

Learn how to keep your website's copyright year updated automatically in Concrete CMS.

How to change the path of a group of pages
Dec 23, 2024
By myq.

Change the canonical path without breaking things

Bi-directional Express associations
Dec 18, 2024
By myq.

Set up associations between Express entries in both directions

Display Express Data Across Multiple Sites
Dec 17, 2024
By myq.

A guide to configuring Express entities and the Express Entry List block to ensure proper data display across multiple sites.

Customize locale icons
Oct 29, 2024
By myq.

How to customize locale (language region) flags

Concrete CMS Caching Guide
Oct 16, 2024

An overview of types of caching in Concrete and considerations when using them.

Improvements?

Let us know by posting here.