Skip to content

Create 301 redirect for all 404 pages to the homepage (404 with any URL combination)

I’m trying creating a redirect for all the 404 pages straight to my homepage. I have tried creating it through .htaccess but seems like it does not worked. .htaccess may ask for the old url & a new url

Redirect 301 old-url-key new-url-key

This is not suitable in my case. Tried generic rule but that also don’t worked. Either it is redirecting all the pages to the homepage. OR specified url to the homepage. I want to permanent redirect only 404 pages that could occur with any url_key combination and 301 redirected to homepage.

Is there a way to achieve it via .htaccess OR module?

I have also tried it with a module but it creates a 302 redirect even I have made it to 301 programmatically. Below is the code snippet for module

<?php

namespace YourModuleController;

use MagentoFrameworkAppRouterNoRouteHandlerInterface;
use MagentoFrameworkAppRequestInterface;
use MagentoFrameworkAppResponseInterface;
use MagentoFrameworkUrlInterface;

class NoRouteHandler implements NoRouteHandlerInterface
{
    protected $response;
    protected $url;

    public function __construct(
        ResponseInterface $response,
        UrlInterface $url
    ) {
        $this->response = $response;
        $this->url = $url;
    }

    public function process(RequestInterface $request)
    {
        $homeUrl = $this->url->getUrl('');
        $this->response->setStatusHeader(301, '1.1', 'Moved Permanently');
        $this->response->setRedirect($homeUrl, 301);

        return false;
    }
}
<?xml version="1.0"?>

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">

    <type name="MagentoFrameworkAppRouterNoRouteHandlerList">
        <arguments>
            <argument name="handlerClassesList" xsi:type="array">
                <item name="redirect404" xsi:type="array">
                    <item name="class" xsi:type="string">YourModuleControllerNoRouteHandler</item>
                    <item name="sortOrder" xsi:type="string">20</item>
                </item>
            </argument>
        </arguments>
    </type>
</config>