Question

I facing issue while redirect from observer file. Actually code worked on localhost but on the server it's not working. Here is the code

public function execute(\Magento\Framework\Event\Observer $observer)
{
    $route = $this->request->getControllerName();
    $url = $this->url->getUrl('customer/account/login');
    if($this->getStoreCode() == 'default'){
        if (!$this->customerSession->isLoggedIn()) {
            if($this->_state->getAreaCode() != 'adminhtml') {
                if(strpos($this->request->getPathInfo(), '/customer/account/') !== 0 || $route == 'noroute') {
                    $observer->getControllerAction()->getResponse()->setRedirect($url);
                }
            }
        }
    }
}

It is not working while controller is noroute. Can anyone please suggest if faced same issue.

No correct solution

OTHER TIPS

Use this code for redirect

use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;

class [YourClass] implements ObserverInterface
{
    /**
     * @var \Magento\Framework\App\ResponseFactory
     */
    private $responseFactory;

    /**
     * @var \Magento\Framework\UrlInterface
     */
    private $url;

    public function __construct(
        ......
        \Magento\Framework\App\ResponseFactory $responseFactory,
        \Magento\Framework\UrlInterface $url,
        ......
    ) {
        $this->responseFactory = $responseFactory;
        $this->url = $url;
    }

    public function execute(Observer $observer)
    {
        $redirectionUrl = $this->url->getUrl('[ModuleName]/[ModuleName]/[[Action]');
        $this->responseFactory->create()->setRedirect($redirectionUrl)->sendResponse();

        return $this;
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top