Magento gets current URL: Methods to get current url and base URL in Magento 2?

Magento getting the current URL is one of the tasks required in many situations when running a Magento 2.4.4 store, for example, creating the URL for a CMS or a blog page, or developing a development site. Therefore, methods to get the base URL and current URL in Magento 2 is the next topic Magesolution guides you today. Let’s do it by using the code snippet in the following two steps.

How to get the current URL in Magento

URL in Magento

As a developer, you will many times require to get Magento to get the current URL or base URL. With Magento 1 version, it was very easy to get the base URL using Mage::getBaseUrl(); However, it is not easy in Magento 2. You can follow the two methods to Magento to get the current URL:

  • Dependency Injection (DI)
  • Object Manager

Although the 2nd solution is not recommended as it consumes extensive resources, it does provide the solution and can be used as an alternative.

Related post: 

>>Magento URL rewrites: How to create it in Magento 2

Method 1: 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);
    }
}

Method 2: Using Object Manager

Using the following command line will allow you to get the base and current URL using object manager in Magento 2.

$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

How to Change Base URLs in Magento 2

Base URLs

Configure the insecure base URLs:

  • Go to Magento 2 backend, and move to Stores > Settings > Configuration.
  • On the left menu, under the General section, you click Web.
  • Expand the Base URLs section. Enter the insecure (HTTP) Base URL for your site. Ensure to end the URL with a forward slash (“/”).
  • If you don’t want to use a secure base URL for the Admin (Optional),   follow the below steps:
    1. Next step, you expand the Base URLs (Secure) section.
    2. Enter your unsecured (HTTP) base URL into the Secure Base URL field. The URL should be the same in both the Base URLs and Base URLs (Secure) sections.
  • Enter the Save Config button.
  • Configure the secure base URLs

However, if your domain gets a valid security certificate, you can configure the URLs for either the storefront and Admin—or both—to run over a secure (HTTPS) channel.

  • Go to Magento 2 backend, and move to Stores > Settings > Configuration.
  • On the left menu, under the General section, choose Web.
  • Expand the Base URLs (Secure) section. Then, follow these steps:
    • To use a secure (HTTPS) for the storefront, click the Secure Base URL, followed by a forward slash (“/”).
    • If you plan to run the entire storefront over a secure (HTTPS) channel, set Use Secure URLs on Storefront to Yes.
    • If you plan to run the entire Admin over a secure (HTTPS) channel, set Use Secure URLs in Admin to Yes.
  • Click the Save Config button.

Using command line

  • Use SSH to log in to your Magento hosting server.
  • Follow the below syntax
    mysql -u $database_user -p $database_name 
  • Fill in your password when prompted.
  • Access the database by following the below syntax, where the database is the database name.
    use database 
  • Follow the below command. This will show the current base_urls set in Magento 2.
    select * from core_config_data where path like '%base%url%';
  • To change the base URLs, use the below commands:
update core_config_data set value = 'http://example.com/' where path = 'web/unsecure/base_url';
update core_config_data set value = 'https://example.com/' where path = 'web/secure/base_url';

How to get the current URL in Magento 2 blocks and templates?

the current URL in Magento 2
  • First of all, you need to generate a new block in your plugin. For instance, we have made Block/Test.php with the following syntax
<?php

namespace <Vendor>\<Module>\Block;

use Magento\Store\Model\StoreManagerInterface;
class Test extends \Magento\Framework\View\Element\Template
{
 /**
 * @var QuoteEmail
 */
 private $storeManager;
public function __construct(
 StoreManagerInterface $storeManager,
 \Magento\Framework\View\Element\Template\Context $context,
 array $data = []
 ) {
 $this->storeManager = $storeManager;
 parent::__construct($context, $data);
 }
public function getCurrentUrl() {
 return $this->storeManager->getStore()->getCurrentUrl();
 }
  • Next step, you need to generate a template file for this block in the view/frontend/templates/ folder. In case, we have made test.phtml. There is 2 solution for how you can get the current URL parameters in the Magento 2 template. See the example:
<?php
//1 way
$block->escapeUrl($block->getUrl('*/*/*', ['_current' => true, '_use_rewrite' => true]));
//2 way
$block->escapeUrl($block->getCurrentUrl());
?>

Conclusion

That’s all about Magento getting the current URL and base URL in Magento.  If you have any errors when following our guide, then you can get in touch with our Magento Website Development services for any free support. Besides, if you are looking out for a cost-effective Magento package for your eCommerce store, then look nowhere other than Magesolution. We not only offer an affordable price for all sizes and budgets but also ensure that it helps your online business grow and sustain. Contact us for a free consultation!