How to redirect to previous page magento 2?

In Your Controller write following code:

namespace Company\Module\Controller\Index;
use Magento\Framework\Controller\ResultFactory; 

class Actionname name extends \Magento\Framework\App\Action\Action
{      
    public function execute()
    {
        $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);

        // Your code

        $resultRedirect->setUrl($this->_redirect->getRefererUrl());
        return $resultRedirect;
    }
}

This code works for me.Hope it will help you too.


This could also be a valid answer in a shorter form Magento 2.0.4

namespace Vendorname\Modulename\Controller\Adminhtml\Index;
class Fetch extends \Magento\Backend\App\Action
{
    public function execute()
    {
        // TODO: Implement execute() method.
        $this->_redirect($this->_redirect->getRefererUrl());
    }
}

Please use this code in your controller class:

$resultRedirect = $this->resultRedirectFactory->create();
$resultRedirect->setRefererUrl();
return $resultRedirect;

Here resultRedirectFactory is a class variable that can be inherited in your class from there parents.

To check if referral URL is set or not, Please print the $_SERVER variable first. This code is working for me.

Tags:

Magento2