Usually, when you visit a website, you will go to the first homepage, but in some cases, you don’t want the first page to be the homepage, you want to redirect it to another path. This article will show you how to make an auto-redirect in magento 2.
Step by step
Step 1: Create Events
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<event name="controller_action_predispatch">
<observer name="magepow_controller_action_predispatch" instance="Magepow\Autoredirect\Observer\Autoredirect" />
</event>
</config>
Step 2: Create Observer
namespace Magepow\Autoredirect\Observer; use Magento\Framework\Event\ObserverInterface; use Magento\Framework\Event\Observer; class Autoredirect implements ObserverInterface{ protected $http; /** @var \Magento\Customer\Model\Session */ protected $customerSession; protected $productModel; protected $productRepository; protected $url; /** * @param \Magento\Framework\UrlInterface $url * @param \Magento\Framework\App\Response\Http $http * @param \Magento\Customer\Model\Session $customerSession */ public function __construct( \Magento\Framework\UrlInterface $url, \Magento\Framework\App\Response\Http $http, \Magento\Customer\Model\Session $customerSession, \Magento\Catalog\Model\Product $product, \Magento\Catalog\Api\ProductRepositoryInterface $productRepository ) { $this->url = $url; $this->http = $http; $this->customerSession = $customerSession; $this->productModel = $product; $this->productRepository = $productRepository; } /** * Manages redirect */ public function execute(Observer $observer) { if($observer->getRequest()->getFullActionName() == 'cms_index_index') { $urlOld = $this->url->getUrl("/"); $endpointHelper = "women/tops-women/jackets-women.html"; $urlEndPoint = $urlOld . $endpointHelper; return $this->http->setRedirect($urlEndPoint,301); } return; }
Save then cache flush to check the result.
Hope this guide help you!