Generating An Automatic 301 Redirect Via Csv Magento 2

Sometimes you want to update the new URL for the product but still want the old URL to work and automatically redirect to the new URL this is beneficial for SEO. Today I will guide you to do this through a few steps.

 

You need to overwrite the file \vendor\magento\module-catalog-url-rewrite\Observer\AfterImportDataObserver.php

 

Step 1:

Create di.xml under /app/code/Magepow/Custom/etc/

 

File: /app/code/Magepow/Custom/etc/di.xml

<?xml version="1.0"?>
    <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
        <preference for="Magento\CatalogUrlRewrite\Observer\AfterImportDataObserver" type="Magepow\Map\Observer\AfterImportDataObserver"/>
    </config>

Step 2:

Copy
\vendor\magento\module-catalog-url-rewrite\Observer\AfterImportDataObserver.php
To
\app\code\Magepow\Custom\Observer\AfterImportDataObserver.php

 

Now update AfterImportDataObserver.php as below

File:\app\code\Magepow\Custom\Observer\AfterImportDataObserver.php

<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
namespace Magepow\Map\Observer;

/**
 * Class AfterImportDataObserver
 *
 * @SuppressWarnings(PHPMD.TooManyFields)
 * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
 */
use Magento\Framework\Event\Observer;

class AfterImportDataObserver extends \Magento\CatalogUrlRewrite\Observer\AfterImportDataObserver
{
    public function execute(Observer $observer)
    {
        $this->import = $observer->getEvent()->getAdapter();
        if ($products = $observer->getEvent()->getBunch()) {
            foreach ($products as $key => $product) {
                $product['save_rewrites_history'] = 1;
                $this->_populateForUrlGeneration($product);
            }
            $productUrls = $this->generateUrls();
            if ($productUrls) {
                $this->urlPersist->replace($productUrls);
            }
        }
    }
}

Step 3:

Now install the custom module and refresh Magento cache

 

php bin/magento setup:upgrade

php bin/magento setup:di:compile

php bin/magento cache:flush

 

Done. Hope this article will help you in some way.