0

How to redirect Product Detail Page to 404 or Home Page in Magento 2.4.

I don't want user to see product detail page in my store.

Any help is appreciated. Thanks.

1
  • Please check with my answer. Commented Jul 5, 2021 at 11:59

1 Answer 1

1

You can use controller_action_predispatch_catalog_product_view event to redirect user to 404 or home page.

In your custom module create

Vendor/MyModule/etc/frontend/etc.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="controller_action_predispatch_catalog_product_view">
        <observer name="custom_pdp_redirect" instance="Vendor\MyModule\Observer\Predispatch"/>
    </event>
</config>

Vendor/MyModule/Observer/Predispatch.php

<?php
namespace Vendor\MyModule\Observer;

use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;

class Predispatch implements ObserverInterface
{

    protected $_redirect;
    protected $_storeManager;
    protected $_url;

    public function __construct(
        \Magento\Framework\App\Response\Http $redirect,
        \Magento\Framework\UrlInterface $url,
        \Magento\Store\Model\StoreManagerInterface $storeManager
    )
    {
        $this->_redirect = $redirect;
        $this->_storeManager = $storeManager;
        $this->_url = $url;
    }

    public function execute(Observer $observer)
    {
        // To redirect to home page
        $homePageUrl  = $this->_storeManager->getStore()->getBaseUrl();
        $this->_redirect->setRedirect($homePageUrl, 301);

        // To redirect to 404 page
        $norouteUrl = $this->_url->getUrl('noroute');
        $this->_redirect->setRedirect($norouteUrl, 301);
    }
}

Thanks!

2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.