I need to redirect customers back to the previous page when a customers get registered or log in to the account like when a customers need to add a review and need to log in to their account before making any comments. So currently Magento 2.1.6 redirects to customer account page when a customers want to review the product.

Does anyone has a solution?


You can follow the following approach:

=>Save the referrer url in session when customer is redirected to login page. You can get the referrer url and set that url by the help of below code:

$referrerurl = $this->_redirect->getRefererUrl();

=> Then after login you can use that url to redirect previous page as shown below:

return $resultRedirect;

To redirect to the previous url after customer login Magento uses refer parameter in login url. If you want to get Login url with refer param in your custom template the add this code in your block file

protected $urlEncoder;

In __contruct function initialise urlEncoder class

public function __construct(
    \Magento\Framework\View\Element\Template\Context $context,
    \Magento\Framework\Url\EncoderInterface $urlEncoder,
    array $data = []
) {
    $this->urlEncoder = $urlEncoder;
    parent::__construct($context, $data);

and then create and set login url like this -

protected function _construct()
    $queryParam = $this->urlEncoder->encode(
            $this->getUrl('*/*/*', ['_current' => true])
                [Url::REFERER_QUERY_PARAM_NAME => $queryParam]

In your template you can get Login Url with refer parameter by $block->getLoginLink();

Not the answer you're looking for? Browse other questions tagged or ask your own question.