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,
Let’s see the implementation of all the possible methods below:
1) Get Base URL
/**
* @var \Magento\Store\Model\StoreManagerInterface $this->_storeManager
*/
$this->_storeManager->getStore()->getBaseUrl();
2) Get Base URL without index.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
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$storeManager = $objectManager->get('\Magento\Store\Model\StoreManagerInterface');
$storeManager->getStore()->getBaseUrl();
4) Get Base URL in config.xml file
{{config path='web/unsecure/base_url'}}
5) Get the Base URL in the layout .xml file
<reference name="head">
<action method="addLinkRel">
<rel>canonical</rel>
<href>{{baseUrl}}customer/account/login</href>
</action>
</reference>
6) Get Media Base URL
/**
* @var \Magento\Store\Model\StoreManagerInterface $this->_storeManager
*/
$this->_storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);
7) Get the Store Link URL
/**
* @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
echo $this->getUrl('pub/media/uploads/',
['_secure' => $this->getRequest()->isSecure()]).'banner_video.mp4';
9) Get a Custom URL link in Block
echo $this->getUrl('about-us');
10) Get Static Content URL in Block
/**
* @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?
Leave a Comment