How to redirect 404 error page in Magento 2

Problem: How can we 301 redirect all 404 error pages in Magento 2. What files need to be modified to redirect all 404 pages. We try to Magento admin redirect all page to another page and. But Magento admin does not redirect 301. And used the .htaccess code does not work. It’s important to note that this will still return a 404 status code. So if you’re trying to 301 redirect 404’s for the sake of google or another search engine, then this isn’t the solution.

Solution: Firstly you can open FTP or cPanel, then go throw the below file path. That is a simple solution for the 301 redirections 404 error page!

/var/www/html/vendor/magento/module-cms/Controller/Router.php

Showing old code like this:

    /** @var \Magento\Cms\Model\Page $page */
    $page = $this->_pageFactory->create();
    $pageId = $page->checkIdentifier($identifier, $this->_storeManager->getStore()->getId());
    if (!$pageId) {
        return null;
    }

Replace with the below code:

    /** @var \Magento\Cms\Model\Page $page */
    $page = $this->_pageFactory->create();
    $pageId = $page->checkIdentifier($identifier, $this->_storeManager->getStore()->getId());
    if (!$pageId) {
        header("HTTP/1.1 301 Moved Permanently");
        header("Location: https://www.example.com/abcd.php");
        exit();
        return null;
    }

Then clear and flush the cache for your project:

sudo php bin/magento cache:clean
sudo php bin/magento cache:flush

Thanks for your reading this article, if this article is helpful for your project. So please comment on the same and share your friend’s circle.

Please follow and like us:
error

2 thoughts on “How to redirect 404 error page in Magento 2”

  1. For Magento 1.9.x

    /app/code/core/Mage/Cms/controllers/IndexController.php

    Old Code :
    public function noRouteAction($coreRoute = null)
    {
    $this->getResponse()->setHeader(‘HTTP/1.1′,’404 Not Found’);
    $this->getResponse()->setHeader(‘Status’,’404 File not found’);

    $pageId = Mage::getStoreConfig(Mage_Cms_Helper_Page::XML_PATH_NO_ROUTE_PAGE);
    if (!Mage::helper(‘cms/page’)->renderPage($this, $pageId)) {
    $this->_forward(‘defaultNoRoute’);
    }
    }
    ————————————————————————
    Replace with this code:

    public function noRouteAction($coreRoute = null)
    {
    header(“HTTP/1.1 301 Moved Permanently”);
    header(“Location: https://example.co.uk/“); die;

    $this->getResponse()->setHeader(‘HTTP/1.1′,’404 Not Found’);
    $this->getResponse()->setHeader(‘Status’,’404 File not found’);

    $pageId = Mage::getStoreConfig(Mage_Cms_Helper_Page::XML_PATH_NO_ROUTE_PAGE);
    if (!Mage::helper(‘cms/page’)->renderPage($this, $pageId)) {
    $this->_forward(‘defaultNoRoute’);
    }
    }

Leave a Reply

Your email address will not be published. Required fields are marked *