Jigar KarangiyaJigar Karangiya

Magento 2: How to Get Base URL?

JK
Jigar Karangiya
· 1 min read
Magento 2: How to Get Base URL?

As a Magento developer, you are required to get a Magento 2 Base URL in various cases,

Today we’ll look at some instances of how to access the Base URL programmatically in Magento 2.

According to the DevDocs,

Each website in an Adobe Commerce or Magento Open Source installation has a base URL that is assigned to the storefront, and another URL that is assigned to the Admin.

Let’s see the implementation of all the possible methods below:

1) Get Base URL

php
/**
* @var \Magento\Store\Model\StoreManagerInterface $this->_storeManager
*/
$this->_storeManager->getStore()->getBaseUrl();

2) Get Base URL without index.php

php
/**
* @var \Magento\Store\Model\StoreManagerInterface $this->_storeManager
*/
$this->_storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_WEB);

3) Get Base URL using Object Manager

php
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$storeManager = $objectManager->get('\Magento\Store\Model\StoreManagerInterface');
$storeManager->getStore()->getBaseUrl();

4) Get Base URL in config.xml file

text
{{config path='web/unsecure/base_url'}}

5) Get the Base URL in the layout .xml file

xml
<reference name="head">
    <action method="addLinkRel">
        <rel>canonical</rel>
        <href>{{baseUrl}}customer/account/login</href>
    </action>
</reference>

6) Get Media Base URL

php
/**
* @var \Magento\Store\Model\StoreManagerInterface $this->_storeManager
*/
$this->_storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);
php
/**
* @var \Magento\Store\Model\StoreManagerInterface $this->_storeManager
*/
$this->_storeManager->getStore()
     ->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_LINK);

8) Get the Base URL from the Root Directory

php
echo $this->getUrl('pub/media/uploads/',
['_secure' => $this->getRequest()->isSecure()]).'banner_video.mp4';
php
echo $this->getUrl('about-us');

10) Get Static Content URL in Block

php
/**
* @var \Magento\Store\Model\StoreManagerInterface $this->_storeManager
*/
$staticUrl = $this->_storeManager->getStore()->getBaseUrl(
\Magento\Framework\UrlInterface::URL_TYPE_STATIC);

That’s it!!

Feel free to share the post and use the Comments section below if you have any queries.

Thanks, See you in the next tutorial. Happy Coding !!

You may also like,

Magento 2: How to get a dynamic Base URL Path in XML?

How to remove/disable add to compare in Magento 2?

How to Show/Hide one field based on another field in UI Component forms in Magento 2?

Written by Jigar Karangiya, Adobe Commerce & Magento 2 developer.

More about me

Related posts