Programmatically: How to create custom Magento routing
Step 1: Create a new module
Create a new directory for your module, e.g., MyCompany_CustomRoute, and inside it, create the following files: app/code/local/MyCompany/CustomRoute/etc/config.xml app/code/local/MyCompany/CustomRoute/etc/module.xml app/code/local/MyCompany/CustomRoute/controllers/IndexController.php config.xml
<?xml version="1.0"?>
<config>
<modules>
<MyCompany_CustomRoute>
<version>1.0.0</version>
</MyCompany_CustomRoute>
</modules>
<global>
<routes>
<custom_route translate="label">
<label>Custom Route</label>
<use>standard</use>
<args>
<module>MyCompany_CustomRoute</module>
<factory>MyCompany_CustomRoute_Controller_Route</factory>
</args>
</custom_route>
</routes>
</global>
</config>
module.xml
<?xml version="1.0"?>
<config>
<modules>
<MyCompany_CustomRoute>
<active>true</active>
<codePool>local</codePool>
</MyCompany_CustomRoute>
</modules>
</config>
IndexController.php
namespace MyCompany\CustomRoute\Controllers;
class IndexController extends Mage_Core_Controller_Varien_Action
{
public function indexAction()
{
// This action will be triggered when the custom route is accessed
$this->renderLayout();
}
}
Step 2: Register the route
In your module's etc/module.xml file, add the following code:
\Magento\Framework\App\Route\RouterMatch::class,
'MyCompany_CustomRoute_IndexController',
'index',
'Magento\Framework\App\Action\Action'
)
->addRouter('custom_route');
Step 3: Clear caches
Clear your Magento cache by running the following command:
php bin/magento cache:clean
Step 4: Test the custom route
Access your custom route by navigating to http://your-magento-store.com/custom-route. You should see the output of the indexAction method in your controller.