How to Create Referer URL in Magento 2
Referer URL is the address of the webpage where a person clicked a link that sent them to your page. Referer is the webpage that the visitor was on before landing on your page.
When a non-logged in user tries to add the product to the wishlist, the default Magento 2 generates one referer URL and redirects that user to the login page. For example, if you write customer/account after your store URL without logging in, Magento 2 automatically redirects you to the login page using the referer URL.
It’s the default behaviour of the Magento 2, but what if you want the same concept in other pages and functionalities on your store also?
You can create referer URL in Magento 2 to implement the below functionalities in your store.
- Restrict user to access order page directly without login.
- Direct URL access restriction without logging in.
- Restrict payments using a specific method for non-logged-in users.
Follow the below solution and restrict the user to access your pages directly without login and get rid of unauthenticated users.
Method to Create Referer URL in Magento 2
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
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; } } |
You are always welcome to mention your doubts regarding this solution in the Comments section below.
I would be glad to help you.
Feel free to share this solution with Magento Community via social media.
Thank You.
Jignesh Parmar
An expert in his field, Jignesh is the team leader at Meetanshi and a certified Magento developer. His passion for Magento has inspired others in the team too. Apart from work, he is a cricket lover.
Prev
Opacity vs RGBA: Which One is Better in CSS?
How to Make Column Sorting “False” Using UI Component in Magento 2
Next