Hello Magento Friends,
In today’s Magento 2 tutorial, I am going to figure out How to Add URL Rewrite Programmatically in Magento 2.
You may require customers to redirect from the old URL to a new address. If the old address is not redirected to the new address, you may lose website traffic. Enabling URL rewrite for Magento 2 helps to redirect customers to new URL addresses easily. URL rewrite is used to make existing URLs more search-friendly.
Here we will learn about Adding URL Rewrite Programmatically in Magento 2.
Let’s check the steps
Steps to Add URL Rewrite Programmatically in Magento 2:
Step 1: To generate the constructor, you have to use the below block of code in your controller file. Here, we have used the Magento\UrlRewrite\Model\UrlRewriteFactory instance and create its object($urlRewriteFactory).
public function __construct(
$this->urlRewriteFactory = $urlRewriteFactory;
public function execute()
$urlRewrite = $this->urlRewriteFactory->create();
/*if you want to rewrite url for “custom” set entity type*/
/*set current store ID */
/*set 0 as this url is not created by system */
/* unique identifier - place random unique value to ID path */
/* set actual url path to target path field */
/* set requested path which you want to create */
/* set the type of Redirect */
/* save URL rewrite rule */
Hence, this way you can Add URL Rewrite Programmatically in Magento 2. If you have any queries feel free to ask me. Share the article with other developers.