Select Page

Magento 2: How to Create And Use Referrer URL.

Gaurav Singh
Published: September 12, 2022

Hello Friends!!!

In this article, we will learn how we Create and use the Referrer URL. But Before creating a referral URL let us understand what a referral URL is.

Referer URL is the web address where a guest clicked a referral link that redirects them to your page.
The referrer is the address the guest was on before they came to your page. For a basic example suppose we have created a custom page in Magento and we have added some functionality to this page we want no one can use this feature/functionality without login. If a guest tries to access this page without login then the guest will be automatically redirected to the login page and after logging in the guest will be redirected to the same page from where the guest came.

Magento 2 uses this behavior by default. But if you want the same behavior applied to other custom pages and functionality on our store? So you can create a referral URL.

Method to Create Referer URL Using Controller

use Magento\Framework\UrlInterface;
 
class Index extends Action\Action
{
    protected $urlInterface;
 
    public function __construct(Action\Context $context, UrlInterface $urlInterface)
    {
        $this->urlInterface = $urlInterface;
        return parent::__construct($context);
    }
 
    public function execute()
    {
        $url = $this->_redirect->getRefererUrl();
        $login_url = $this->urlInterface
            ->getUrl('customer/account/login',
                array('referer' => base64_encode($url))
            );
        $resultRedirect = $this->resultRedirectFactory->create();
        $resultRedirect->setUrl($login_url);
        return $resultRedirect;
    }
}

Hope this will be helpful.
Thanks

Source: webkul.com