Magento 2 Routing Rewrite Controller

We can rewrite controller with the help of router. Magento provides the attribute before/after to config the module sort order which define what module controller will be find first.

For example, if we want to rewrite the controller customer/account/login, we will define more route in the route.xml like this:

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">
 <router id="standard">
 <route frontName="first" id="first">
 <module name="PHPCodez_First"/>
 <route id="customer">
 <module name="PHPCodez_First" before="Magento_Customer" />
namespace PHPCodez\First\Controller\Account;
use Magento\Customer\Controller\Account;

class Login extends \Magento\Customer\Controller\AbstractAccount {
 public function execute(){
 die('PHPCodez Overridden Successfully. Cheers !!!! ');

And the controller file: app/code/PHPCodez/First/Controller/Account/Login.php

So the frontController will find the Login action in our module first, if it’s found, it will run and the Login action of Magento_Customer will not be run.

Now lean the cache and load the URL and the message ‘PHPCodez Overridden Successfully. Cheers !!!! ‘ will be displayed on the screen.

php bin/magento cache:flush

Leave a Reply

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