How to get Magento 2 base URL?

In magento 2.

If you want to get Base url ,then you can try below code:

/**
* @var \Magento\Store\Model\StoreManagerInterface $this->_storeManager
*/

$this->_storeManager->getStore()->getBaseUrl();

Where $this->_storeManager instance of \Magento\Store\Model\StoreManagerInterface

this above code will give you result

http://www.example.com (If Seo rewrite is enable)

And http://www.example.com/index.php (If Seo rewrite is not enable)

If you want Base URL without index.php

$this->_storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_WEB)

See in details at magento2 get base url and media url and static url

Using Object Manager

Base Url:

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

Base Url without index.php

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

For getting media base url:

$this->_storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);

for getting link url:

$this->_storeManager->getStore()
           ->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_LINK);

Edit

For getting the $this->_storeManager You should call inject \Magento\Store\Model\StoreManagerInterface $storeManager

at __construct( ) function at block class

just like :

public $_storeManager;
  public function __construct(
      \Magento\Store\Model\StoreManagerInterface $storeManager,
       .....
    ) {
       ...
  $this->_storeManager=$storeManager;
    }

Updated:

Also,you can get base url directly at phtml using direct call of object Manager.

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

Note: Directly call of object manager is not good idea. If you want base url at phtml then inject StoreManagerInterface at block


Simply use this command if you are using a class that extends \Magento\Framework\View\Element\Template.

$this->getBaseUrl()

If not, you can use this:

$this->_storeManager->getStore()->getBaseUrl()

Or if you are using it in a PHTML template use:

$block->getBaseUrl()

In Magneto2: This is way to get Url link in PHTML file:

echo $this->getUrl('about-us')

I hope it will work for you