Magento 2, You can redirect to any custom URL from Observer file. When you have created event observer for any specific event and you want to redirect to any URL in a site, You can redirect from observer simply by calling below code,
Create an observer file under app/code/{Packagename}/{Modulename}/YourEventObserver.php
In the following observer, I am redirecting to the (“customer/account/login”) login page of site,
I am displaying two way to redirect to Custom URL from Observer,
1)
$controller = $observer->getControllerAction(); $this->redirect->redirect($controller->getResponse(), 'customer/account/login');
2)
$controller = $observer->getControllerAction(); $url = $this->getUrl('customer/account/login'); //Magento\Framework\UrlInterface $url $controller->getResponse()->setRedirect($url);
Check for Demo 1,
<?php namespace Magento\Captcha\Observer; use Magento\Framework\Event\ObserverInterface; class CheckForgotpasswordObserver implements ObserverInterface { protected $redirect; public function __construct( \Magento\Framework\App\Response\RedirectInterface $redirect ) { $this->redirect = $redirect; } /** * Redirect to login page * * @param \Magento\Framework\Event\Observer $observer * @return $this */ public function execute(\Magento\Framework\Event\Observer $observer) { /** @var \Magento\Framework\App\Action\Action $controller */ $controller = $observer->getControllerAction(); $this->redirect->redirect($controller->getResponse(), 'customer/account/login'); return $this; } }
In above execute() function,
When you need redirect to specific URL, You need to pass your custom URL instead of customer/account/login as the second parameter in redirect() function.