Magento 2 Routing

The Route will define name for a module which we can use in the url to find the module and execute the controller action.

In Magento 2, the request url will be

In that url, you will see the front_name which will be use to find the module. The router define this name for each module by define in routes.xml

Create custom route on frontend

To register a frontend route, we must create a routes.xml file:

File: app/code/PHPCodez/First/etc/frontend/routes.xml

<?xml version="1.0" ?>
<config xmlns:xsi="" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
 <!--Use router 'standard' for frontend route-->
 <router id="standard">
 <!--Define a custom route with id and frontName-->
 <route frontName="first" id="first">
 <!--The module which this route match to-->
 <module name="PHPCodez_First"/>

The id attribute is a unique string which will identify this route. You will use this string to declare the layout handle for the action of this module

The frontName attribute is also a unique string which will be shown on the url request.

The url to this module should be

And the layout handle for this action is: first_controller_action.xml So with this example path, you must create the action class in this folder: {namespace}/{module}/Controller/{Controller}/{Action}.php

Create custom route on admin

This route will be same as the frontend route but you must declare it in adminhtml folder with router id is admin.

File: app/code/PHPCodez/First/etc/adminhtml/routes.xml

<?xml version="1.0"?>
<config xmlns:xsi="" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
 <!--Use router 'admin' for admin route -->
 <router id="admin">
 <!--Define a custom route with id and frontName -->
 <route id="phpcodez_first" frontName="phpcodez_first">
 <!--The module which this route match to-->
 <module name="PHPCodez_First"/>

The url of the admin page is the same structure with frontend page, but the admin_area name will be added before route_frontName to recognize this is a admin router.

The controller action for admin page will be added inside of the folder Controller/Adminhtml



Leave a Reply

Your email address will not be published. Required fields are marked *