Question

Today I am trying to redirects 301 pro-grammatically. But I have problem from

$this->_responseFactory->create()->setRedirect($CustomRedirectionUrl , 301)->sendResponse();

line. I have entered

http://192.168.10.144/localwebsite/ProductDetails.asp?ProductCode=10039&CartID=1

URL, Here I get the Product URL by using 10039 SKU, and I appended product URL to Base URL $url. but it is not working for me.

My code is

Observer

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/Event/etc/events.xsd">

   <event name="controller_action_predispatch">
        <observer name="custom_url_rewrite" instance="Company\CustomURLRewrite\Observer\RedirectOldToNewUrl" />
    </event>

</config>

RedirectOldToNewUrl.php

<?php

namespace Company\CustomURLRewrite\Observer;

class RedirectOldToNewUrl implements \Magento\Framework\Event\ObserverInterface{


    /* Check here Request query string */
    protected function _getQueryString()
    {
        if (!empty($_SERVER['QUERY_STRING'])) {
            $queryParams = array();
            parse_str($_SERVER['QUERY_STRING'], $queryParams);
            $hasChanges = false;
            foreach ($queryParams as $key => $value) {
                if (substr($key, 0, 3) === '___') {
                    unset($queryParams[$key]);
                    $hasChanges = true;
                }
            }
            if ($hasChanges) {
                return http_build_query($queryParams);
            } else {
                $queryCodes = $_SERVER['QUERY_STRING'];
                $beforeSplit = explode('&',$queryCodes);
                //return $_SERVER['QUERY_STRING'];
                return $beforeSplit[0];
            }
        }
        return false;
    }

    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        if($this->_getQueryString()){
            print_r($this->_getQueryString());

            // Check query string exits in product_id
            if(strpos($this->_getQueryString(),'ProductCode=')!== false){
                /* get Product ifd from query string */
                $sku = str_replace('ProductCode=','',$this->_getQueryString());
                if(!empty($sku)):
                    $product= $this->_productRepository->get($sku);
                    if ($product->getId()) {
                        $storeObj = $this->_storeManager->getStore(1);
                        $storeId = $storeObj->getId();
                        $BaseURL = $storeObj->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_WEB);
                        $url = $BaseURL . $product->getUrlKey();
                        echo $url;
                        //Mage::app()->getResponse()->setRedirect($product->getProductUrl(), 301)->sendResponse();
                        $CustomRedirectionUrl = $this->_url->getUrl($url);
                        $this->_responseFactory->create()->setRedirect($CustomRedirectionUrl , 301)->sendResponse();
                        return;
                    }
                endif;
            }

        }

    }

    /**
    * @var \Magento\Catalog\Model\ProductRepository
    */
    protected $_productRepository;

    /**
    * @var \Magento\Framework\App\ResponseFactory
    */
    protected $_responseFactory;

    /**
    * @var \Magento\Framework\UrlInterface
    */
    protected $_url;

    /**
    * @var \Magento\Store\Model\StoreManagerInterface
    */
    protected $_storeManager;

    public function __construct
    (
        \Magento\Framework\App\ResponseFactory $responseFactory,
        \Magento\Framework\UrlInterface $url,
        \Magento\Store\Model\StoreManagerInterface $storeManagerInterface,
        \Magento\Catalog\Model\ProductRepository $productRepository
    ){
        $this->_storeManager = $storeManagerInterface;
        $this->_responseFactory = $responseFactory;
        $this->_url = $url;
        $this->_productRepository = $productRepository;
    }


}

Any help on this?

Was it helpful?

Solution

In your class declare the variable

/**
     * @var \Magento\Framework\App\ResponseInterface
     */
    protected $_response;

In constructor initialize the object

public function __construct
    (
        \Magento\Framework\App\ResponseInterface $response
    ){

        $this->_response = $response;
    }

Finally add the url to 301 redirects like below

remove below 2 lines

$CustomRedirectionUrl = $this->_url->getUrl($BaseURL);
$this->_responseFactory->create()->setRedirect($CustomRedirectionUrl )->sendResponse();

add below line

$this->_response->setRedirect($url, 301)->sendResponse();

// We need to set up 301 explicitly because 302 redirect is by default.
// See \Magento\Framework\App\Response\HttpInterface::setRedirect():  
// public function setRedirect($url, $code = 302);

now try to clean cache and run your code.

OTHER TIPS

Try adding an exit after the redirect.

$this->_responseFactory->create()->setRedirect($CustomRedirectionUrl , 301)->sendResponse();
exit;
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top