Magento – Magento2 : Not getting proper http referrer url

magento2referral

The code does not show the referrer URL of the website. From which the user has come to the current page. Instead, it is displaying the website base URL any idea why it is happening?
It is working fine on my website. when the user moves from product to contact page etc.
I also tried this too.

echo $_SERVER['HTTP_REFERER'];

but not working.

Here is my current code

 $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
            $redirect = $objectManager->create('\Magento\Framework\App\Response\RedirectInterface');
             echo $redirect->getRefererUrl();

Output: http://www.yourwebsite.com/

Expected Result: http://www.previouswebsite.com/

Best Answer

In PHP you can call simply by, $_SERVER[“HTTP_REFERER”], In Magento 2 Best Practice, you need to call RedirectInterface in your __construct() function and get referrer URL.

public function __construct(
    \Magento\Framework\App\Response\RedirectInterface $redirect
) {
    $this->redirect = $redirect;
}

Call below the line in your function,

echo $this->redirect->getRefererUrl();
echo $this->redirect->getRedirectUrl();

copied from RAKESH JESADIYA blog