Magento – Magento 2 : How to forward controller defaultNoRoute

404404-pagemagento2noroute

I create a custom module in which if data is found the template is shown else I need to show default 404-page content & set the status to 404.

I have tried below code to set the status to 404 without changing the URL(i.e, not redirecting to noroute)

$resultPage->setStatusHeader(404, '1.1', 'Page Not Found');
$resultPage->setHeader('Status', '404 Page Not Found');

But I'm unable to show the default 404 error page content.

I have tried below code to forward the controller to default no route page, but it's not working for me.

$this->_forward('defaultNoRoute');

Can anyone help me out from this? Thanks in advance.

Best Answer

You Can Override Magento\Framework\App\Router\NoRouteHandlerList File In app/code/Vendor/Module/etc/frontend/di.xml

And You Can Add Your Code Like This :-

public function execute()
    {
        $resultLayout = $this->resultPageFactory->create();
        $resultLayout->setStatusHeader(404, '1.1', 'Not Found');
        $resultLayout->setHeader('Status', '404 File not found');
        return $resultLayout;
    }

Reference Link

Create custom 404 page for not-found products