Question

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.

No correct solution

OTHER TIPS

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

Use this class for redirection

public function __construct
(
    \Magento\Framework\Controller\Result\ForwardFactory $forwardFactory
) 
{
    $this->_forwardFactory = $forwardFactory;
}

Now you can redirect to 404 page using this

if(CONDITION)
{
    $resultForward = $this->_forwardFactory->create();
    $resultForward->setController('index');
    $resultForward->forward('defaultNoRoute');
    return $resultForward;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top