magento2 get base url and media url and static url

magento2 get base url and media url and static url

whenever, you are working on  magento2 then a lot of times you need to get base URL and media URL and static url.Most times need base Url.

In here, I am tried to give you to get base ,media ,static urls in magento
At phtml file you need to use below code:

Direct use of Object manager is not the good idea.

Best Practices:

If you have Store Manager Object class at Block/helper/controller/Model at then you can get base url,media url, static content using below codes. Note you will get store Manager Object by Injection of class Magento\Store\Model\StoreManagerInterface.

Use below for getting base URL


Use below for getting base URL with Index.php

 If the seo_rewrite is not enabled  or Pages opening with index.php then 

if give the result like

For getting media url:

For getting link url:

For getting static url:


In several cases, you need to current store base Magento 1.x version you can get base url using Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB));

As Magento2, not used factory patterns, so there has no code like Mage::getBaseUrl(); by which you can base URL.But at Magento2, you should use StoreManager object then using $this->_storeManager->getStore()->getBaseUrl() you can get base url.

Magento2, use interface, injection of class, that you should Inject

at Model, Resource model, Helper classes for getting base URL.

In below example class, I have injected StoreManagerInterface my class



Note that: if you have used any block class which extends base block template

and should avoid injected of store manager interface for that case as extends class already have store Manager object

try below code to get magento2 base URL:

How to get magento2 base url by Object Manager

Using Object manager for getting magento2 base URL then try below once:

Assume that your class has object manager.

If don’t have object manager then try this:

But this type of object manager calls is really bad idea.

Related posts:

3 thoughts on “magento2 get base url and media url and static url

Leave a Reply

Your email address will not be published. Required fields are marked *