Magento 2 – How to Add 410 Header for 404 Pages

404http-error-404url-rewrite

My Magento store experiences a high amount of products that get added and then deleted. I have been asked to implement a 410 status code on these deleted pages but I am unsure how.

I have installed a extension

Magento-2-Module-PageNotFound

But its only listing the URLs which going to 404 pages.

How can I set all 404 pages to 410 status.

Can I get some help? Thank you in advance.

Best Answer

I have found the solution for this.

I have user this plugin to catch the 404 urls

<?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="Magento\Cms\Controller\Noroute\Index">
        <plugin name="trackNoRoutePages"
                type="Experius\Pvn\Controller\Plugin\TrackNoRoutePages"/>
    </type>
</config>

Here am redirecting them to 410 gone page which I created in Page from content>>pages. and setting headers to 410

<?php

namespace Experius\Pvn\Controller\Plugin;

class TrackNoRoutePages
{
    public function afterExecute(
        \Magento\Cms\Controller\Noroute\Index $subject,
        $return
    ) {

        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $redirect = $objectManager->get('\Magento\Framework\App\Response\Http');

        $storeManager = $objectManager->get('\Magento\Store\Model\StoreManagerInterface');
        $base_url=$storeManager->getStore()->getBaseUrl();
        

        $redirect->setRedirect($base_url.'410-gone');
        $redirect->setStatusHeader(410, '1.1', 'Gone');
        $redirect->setHeader('Status', '410 Gone');

        return $redirect;
    }
}
Related Topic