Get No Route URL Programmatically Magento 2 to redirect to 404 Not found page.
You can redirect to the No Route page using ScopeConfigInterface and UrlInterface to not found action. The default value for the No Route page is the cms/noroute/index.
Fetch the Store Configuration value for the No Route path, and pass that value to the URL interface.
<?php namespace Jesadiya\NoRoute\Model; use Magento\Framework\UrlInterface; use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Store\Model\ScopeInterface; class NoRoute { private ScopeConfigInterface $scopeConfig; private UrlInterface $url; public function __construct( ScopeConfigInterface $scopeConfig, UrlInterface $url ) { $this->scopeConfig = $scopeConfig; $this->url = $url; } /** * No Route url * * @return string */ public function getNoRouteUrl(): string { $defaultNoRouteUrl = $this->scopeConfig->getValue( 'web/default/no_route', ScopeInterface::SCOPE_STORE ); $redirectUrl = $this->url->getUrl($defaultNoRouteUrl); return $redirectUrl; } }
You can see the no route path value from the Admin panel by login to your Magento Admin panel,
Go To Stores -> Configuration -> General -> Web -> Default Pages -> Default No-route URL.
Call from the template or PHP class,
echo $noRouteUrl = $this->getNoRouteUrl();
Output:
http://magento2.docker/cms/noroute/index