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;

Step 2: Add custom URL rewrite in execute method.

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

/* set current store id */

/* this url is not created by system so set as 0 */

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

/* set actual url path to target path field */

/* set requested path which you want to create */

/* set current store id */

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 *