0

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="Magento\Framework\App\RouterList">
        <arguments>
            <argument name="routerList" xsi:type="array">
                <item name="bv_custom" xsi:type="array">
                    <item name="class" xsi:type="string">vendor\module\Controller\Router</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 Vendor\module\Controller;

use Magento\Framework\App\Action\Forward;
use Magento\Framework\App\ActionFactory;
use Magento\Framework\App\ActionInterface;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\App\ResponseInterface;
use Magento\Framework\App\RouterInterface;
use Magento\Framework\Controller\Result\Redirect;
use Magento\Store\Model\StoreManagerInterface;

/**
 * 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;
    }
}
1
  • Do you face any issues, then added description into question. Commented Apr 22 at 13:28

1 Answer 1

0

You can handle redirection directly from the backoffice.

Marketing > Seo > Url Rewrites

No code needed there

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.