Skip to content

Create cutom router for redirecting to homepage || Magento 2

In Magento 2, I want to set custom route, like after baseurl/custom-route/any url it should be redirected to homepage or base url. Here, I had tried to create type of RouterList and extend RouterInterface. As shown below, but it is not working as required.

Please provide solution for this.

I had tried below solution. By creating below di.xml

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="MagentoFrameworkAppRouterList">
        <arguments>
            <argument name="routerList" xsi:type="array">
                <item name="bv_custom" xsi:type="array">
                    <item name="class" xsi:type="string">vendormoduleControllerRouter</item>
                    <item name="disable" xsi:type="boolean">false</item>
                    <item name="sortOrder" xsi:type="string">40</item>
                </item>
            </argument>
        </arguments>
    </type>
</config>

and below is defined controller class Route.php

<?php
namespace VendormoduleController;

use MagentoFrameworkAppActionForward;
use MagentoFrameworkAppActionFactory;
use MagentoFrameworkAppActionInterface;
use MagentoFrameworkAppRequestInterface;
use MagentoFrameworkAppResponseInterface;
use MagentoFrameworkAppRouterInterface;
use MagentoFrameworkControllerResultRedirect;
use MagentoStoreModelStoreManagerInterface;

/**
 * Class Router
 */
class Router implements RouterInterface
{
    private $actionFactory;
    private $response;
    private $storeManager;

    /**
     * Router constructor.
     */
    public function __construct(
        ActionFactory $actionFactory,
        ResponseInterface $response,
        StoreManagerInterface $storeManager
    ) {
        $this->actionFactory = $actionFactory;
        $this->response = $response;
        $this->storeManager = $storeManager;
    }

    public function match(RequestInterface $request): ?ActionInterface
    {
        $identifier = trim($request->getPathInfo(), '/');

        if (strpos($identifier, 'shop') !== false) {
            $resultRedirect = $this->actionFactory->create(Redirect::class);
            $resultRedirect->setUrl($this->storeManager->getStore()->getBaseUrl());
            return $resultRedirect;
        }

        return null;
    }
}