Development

Automatic Redirect by Path in Drupal 8

This example shows how to intercept a Drupal page request, determine if the desired path matches the one we wish to redirect, find the “latest” node of a particular content type, and redirect to that node instead of the original page.

I have a page on my site called Updates. This landing page exists only so that there is a menu item and proper breadcrumb trail; users never get to this landing page. Rather, they’re redirected to the latest update when they attempt to visit the landing page. Updates are nodes of the type update. Each update node (when viewed as a page) shows a Recent Updates block in the sidebar with links to of all of the most recent updates.

The landing page is a Views-based page (so it doesn’t get accidentally deleted). There is also an All Views-based page that lists links to all updates. If the system cannot find the latest update the user will be redirected to the All page.

File Structure

  • mymodule
    • src
      • EventSubscriber
        • MyModuleSubscriber.php
    • mymodule.services.yml

MyModuleSubscriber.php

mymodule.services.yml

Handling Invalid URLs

If you try to use the above code to redirect paths that aren’t valid Drupal resources you will find that the onRequest() method doesn’t get called. You can fix this by changing the weight of your method like this:

 

2 Comments

  • Manoj

    Hi,

    Very nice and simple tutorial. Can you please help me with 404 redirection. I wanted to Redirect the URLs returning a 404 status to the defined closest alternative, or parent category, to reclaim link equity from external domains.

    Example: Suppose I am using URL http://www.mysite.com/about/xyz/ and it return 404 so I wanted to create any module or system that smartly redirect to nearest parent path like “http://www.mysite.com/about/”

Leave a Reply

Your email address will not be published.