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:
- Using Magento Core Method
- Using Object Manager
I have shown the implementation of both the methods below:
Methods to Get Magento 2 Base URL:
Using Magento Core Method
<?php
namespace [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
$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
Thanks.