Question

I have a third-party module installed in my Magento ver 2.3.4-p2 instance.

I need to put a redirect from a file in the module, which is present in app/code/Plazathemes/Blog/Controller/Router.php

What is the code / syntax for Magento2 to redirect any request from any php file to an external url with 301?

UPDATE: Adding full file code of Router.php controller.

<?php
/**
 * Copyright © 2015 PlazaThemes.com. All rights reserved.

 * @author PlazaThemes Team <contact@plazathemes.com>
 */

namespace Plazathemes\Blog\Controller;
/**
 * Blog Controller Router
 */
class Router implements \Magento\Framework\App\RouterInterface
{
    /**
     * @var \Magento\Framework\App\ActionFactory
     */
    protected $actionFactory;

    /**
     * Event manager
     *
     * @var \Magento\Framework\Event\ManagerInterface
     */
    protected $_eventManager;

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

    /**
     * Page factory
     *
     * @var \Plazathemes\Blog\Model\PostFactory
     */
    protected $_postFactory;

    /**
     * Category factory
     *
     * @var \Plazathemes\Blog\Model\CategoryFactory
     */
    protected $_categoryFactory;

    /**
     * Config primary
     *
     * @var \Magento\Framework\App\State
     */
    protected $_appState;

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

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

    /**
     * @param \Magento\Framework\App\ActionFactory $actionFactory
     * @param \Magento\Framework\Event\ManagerInterface $eventManager
     * @param \Magento\Framework\UrlInterface $url
     * @param \Plazathemes\Blog\Model\PostFactory $postFactory
     * @param \Plazathemes\Blog\Model\CategoryFactory $categoryFactory
     * @param \Magento\Store\Model\StoreManagerInterface $storeManager
     * @param \Magento\Framework\App\ResponseInterface $response
     */
    public function __construct(
        \Magento\Framework\App\ActionFactory $actionFactory,
        \Magento\Framework\Event\ManagerInterface $eventManager,
        \Magento\Framework\UrlInterface $url,
        \Plazathemes\Blog\Model\PostFactory $postFactory,
        \Plazathemes\Blog\Model\CategoryFactory $categoryFactory,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        \Magento\Framework\App\ResponseInterface $response
    ) {
        $this->actionFactory = $actionFactory;
        $this->_eventManager = $eventManager;
        $this->_url = $url;
        $this->_postFactory = $postFactory;
        $this->_categoryFactory = $categoryFactory;
        $this->_storeManager = $storeManager;
        $this->_response = $response;
    }

    /**
     * Validate and Match Blog Pages and modify request
     *
     * @param \Magento\Framework\App\RequestInterface $request
     * @return bool
     */
    public function match(\Magento\Framework\App\RequestInterface $request)
    {
        $_identifier = trim($request->getPathInfo(), '/');
        if (strpos($_identifier, 'blog') !== 0) {
            return;
        }

        $identifier = str_replace(array('blog/', 'blog'), '', $_identifier);

        $condition = new \Magento\Framework\DataObject(['identifier' => $identifier, 'continue' => true]);
        $this->_eventManager->dispatch(
            'Plazathemes_blog_controller_router_match_before',
            ['router' => $this, 'condition' => $condition]
        );

        if ($condition->getRedirectUrl()) {
            $this->_response->setRedirect($condition->getRedirectUrl());
            $request->setDispatched(true);
            return $this->actionFactory->create(
                'Magento\Framework\App\Action\Redirect',
                ['request' => $request]
            );
        }

        if (!$condition->getContinue()) {
            return null;
        }

        $identifier = $condition->getIdentifier();

        $success = false;
        $info = explode('/', $identifier);

        if (!$identifier) {
            $request->setModuleName('blog')->setControllerName('index')->setActionName('index');
            $success = true;
        } elseif (count($info) == 2) {
            $store = $this->_storeManager->getStore()->getId();

            switch ($info[0]) {
                case 'post' :
                    $post = $this->_postFactory->create();
                    $postId = $post->checkIdentifier($info[1], $this->_storeManager->getStore()->getId());
                    if (!$postId) {
                        return null;
                    }

                    $request->setModuleName('blog')->setControllerName('post')->setActionName('view')->setParam('id', $postId);
                    $success = true;
                    break;
                case 'category' :
                    $category = $this->_categoryFactory->create();
                    $categoryId = $category->checkIdentifier($info[1], $this->_storeManager->getStore()->getId());
                    if (!$categoryId) {
                        return null;
                    }

                    $request->setModuleName('blog')->setControllerName('category')->setActionName('view')->setParam('id', $categoryId);
                    $success = true;
                    break;
                case 'archive' :
                    $request->setModuleName('blog')->setControllerName('archive')->setActionName('view')
                        ->setParam('date', $info[1]);

                    $success = true;
                    break;

                case 'search' :
                    $request->setModuleName('blog')->setControllerName('search')->setActionName('index')
                        ->setParam('q', $info[1]);

                    $success = true;
                    break;
            }

        }

        if (!$success) {
            return null;
        }

        $request->setAlias(\Magento\Framework\Url::REWRITE_REQUEST_PATH_ALIAS, $_identifier);

        return $this->actionFactory->create(
            'Magento\Framework\App\Action\Forward',
            ['request' => $request]
        );
    }

}
Was it helpful?

Solution 2

I have solved this with below code:

public function match(\Magento\Framework\App\RequestInterface $request)
{
    $this->_response->setRedirect('/');

    //Or elternatively you can also put any external site link and it will 301 redirect as well
    $this->_response->setRedirect('https://stackoverflow.com');
}

Note: above code, I have written in match() function as I already had it in my module class, I have given full php class code in the question.

OTHER TIPS

For redirect you can use this

  1. Add Dependency in construct if it's not there

    protected $resultFactory;
    
    public function __construct(
      \Magento\Framework\Controller\ResultFactory $resultFactory
    ) {
       $this->resultFactory = $resultFactory;
    }
    
  2. Add this line in your function where you want the redirect

    /** @var \Magento\Backend\Model\View\Result\Redirect $resultRedirect */
    $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);
    return $resultRedirect->setPath('your action path here');
    
  3. Or if you are trying to redirect from a controller. you can simply use this

    $this->_redirect('route/controller/action');
    

Try this code :-

public function execute()
{
    $resultRedirect = $this->resultRedirectFactory->create();
    $resultRedirect->setPath('routename/controllerpath/controllername');
    return $resultRedirect;
}

UPDATE

protected $resultRedirect;

public function __construct(\Magento\Framework\Controller\ResultFactory $result){
    $this->resultRedirect = $result;
}

public function execute()
{
    $resultRedirect = $this->resultRedirect->create(ResultFactory::TYPE_REDIRECT);
    $resultRedirect->setUrl($this->_redirect->getRefererUrl());

    return $resultRedirect;         
 }

And most useful this link: Redirect controller in magento 2

Hope this help you.

Thanks

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top