How to Get Magento 2 Base URL
As a Magento 2 developer, I many times require to get Magento 2 base URL.
In good old days of Magento 1, it was easier to get the base URL using Mage::getBaseUrl();
However, it is not the same case in Magento 2.
You can use the two methods to get base URL in Magento 2:
I have shown the implementation of both the methods below:
Methods to Get Magento 2 Base URL:
-
Using Magento Core Method
12345678910111213141516171819202122232425262728293031323334353637<?phpnamespace [Vendor]\[Module]\Helper;use Magento\Framework\App\Helper\AbstractHelper;use Magento\Framework\App\Helper\Context;use Magento\Store\Model\StoreManagerInterface;class Data extends AbstractHelper{protected $storeManager;public function __construct(Context $context,StoreManagerInterface $storeManager){$this->storeManager = $storeManager;parent::__construct($context);}public function getStoreManagerData(){$storeUrl = $this->storeManager->getStore()->getBaseUrl();// get Store Url without index.php$storeUrl = $this->storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_WEB);// get Link Url of store$storeLinkUrl = $this->storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_DIRECT_LINK);// get media Base Url$storeMediaUrl = $this->storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);// get Static content Url$storeStaticUrl = $this->storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_STATIC);}} -
Using Object Manager
1234567$objectManager = \Magento\Framework\App\ObjectManager::getInstance();$storeManager = $objectManager->get('\Magento\Store\Model\StoreManagerInterface');$storeManager->getStore()->getBaseUrl(); // to get Base Url$storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_WEB); // to get Base Url without index.php$storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_LINK); // to get store link url$storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA); // to get Base Media url
That’s it
Feel free to share the post and use the Comments section below if you have any doubts on the topic. I’d be happy to solve it asap.
Thanks.
Sanjay Jethva
Sanjay is the co-founder and CTO of Meetanshi with hands-on expertise with Magento since 2011. He specializes in complex development, integrations, extensions, and customizations. Sanjay is one the top 50 contributor to the Magento community and is recognized by Adobe.
His passion for Magento 2 and Shopify solutions has made him a trusted source for businesses seeking to optimize their online stores. He loves sharing technical solutions related to Magento 2 & Shopify.
Prev
How to Programmatically Set Magento 2 Core Config Data
How to Get Product Collection by Category ID in Magento 2
Next