How to create custom URL Rewrite programmatically in Magento 2

In this Article, we will learn how you can add URL Rewrite programmatically in Magento 2.

What is URL Redirect?

URL Redirect is the SEO term that is used for navigating the visitors to any link which store owners wants. There are two type of redirect:

  • 301 redirect
  • 302 redirect

If you need to add custom URLs programmatically then the solution is here. Here We are going to explain the process to add custom URL using code in controller file.

Step 1: create constructor method

/**
* @var \Magento\UrlRewrite\Model\ResourceModel\UrlRewriteFactory
*/
protected $_urlRewriteFactory;

/**
* @param Context $context
* @param \Magento\UrlRewrite\Model\UrlRewriteFactory $urlRewriteFactory
*/
public function __construct(
	Context $context,
	\Magento\UrlRewrite\Model\ResourceModel\UrlRewriteFactory $urlRewriteFactory
) {
	$this->_urlRewriteFactory = $urlRewriteFactory;
	parent::__construct(
		$context
	);
}

Step 2: Add custom URL rewrite in execute method.

$urlRewriteModel = $this->_urlRewriteFactory->create();

/* set current store id */
$urlRewriteModel->setStoreId(1);

/* this url is not created by system so set as 0 */
$urlRewriteModel->setIsSystem(0);

/* unique identifier - set random unique value to id path */
$urlRewriteModel->setIdPath(rand(1, 100000));

/* set actual url path to target path field */
$urlRewriteModel->setTargetPath("www.mageclues.com/oldModule/oldController/oldAction");

/* set requested path which you want to create */
$urlRewriteModel->setTargetPath("www.mageclues.com/newURL");

/* set current store id */
$urlRewriteModel->save();

Also, you can set path only without domain in requested path and target path.

I hope this article is useful for you. please left comment if you have any queries.

Thank you):

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *