Magento 2How To GuideNovember 4, 2020

How to Add Magento 2 URL Rewrite Programmatically?

How to Add Magento 2 URL Rewrite Programmatically?

What is URL Rewriting?

URL rewriting is the process of making your entire store URLs uniform for the purposes of user readability and search engine friendliness. It makes URLs easier to remember, meaningful, keyword-rich, and easier to index. Consider the following 3 URLs.


The first URL is long, difficult to remember, contains no keyword, gives no information about the content of the page and thus not useful for users and search engines alike.

The second URL is much cleaner and short but does not tell which product it’s going to display.

The last URL is short and meaningful. Both users and search engines can determine the content of the page. It’s a preferred URL structure that is easier to index.

URL rewriting is used to create URLs like the last one and tell servers how to process them.

Quick Note: Ready Made Solution to Import Export URL Rewrites in Magento 2

What is the Need to Add URL Rewrite Programmatically?

You can add URL rewrite manually if you have a few URLs. But this is usually not the case if you have an ecommerce store. You may have tens of categories, subcategories and hundreds of products and CMS pages. Adding URL rewrite for all these pages is a near impossible task. The best way is to do it programmatically.

Magento 2 Add URL Rewrite Programmatically

The URL Rewrite tool lets you change any URL that is associated with a product, category, or CMS page. When the rewrite goes into effect, any links that point to the previous URL are redirected to the new address. Follow the steps below to enable URL rewrite programmatically in Magento 2.

Step 1: Generate a Constructor File

 * @var \Magento\UrlRewrite\Model\ResourceModel\UrlRewriteFactory
protected $_urlRewriteFactory;
 * @param Context $context
 * @param \Magento\UrlRewrite\Model\ResourceModel\UrlRewriteFactory $urlRewriteFactory
public function __construct(
 Context $context,
 \Magento\UrlRewrite\Model\ResourceModel\UrlRewriteFactory $urlRewriteFactory
 $this->_eavAttributeFactory = $eavAttributeFactory;

Step 2: Fill in 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 */

/* save URL rewrite rule */

That’s all about adding URL rewrite programmatically in Magento 2. Any questions or comments regarding URL rewrites in Magento 2 are welcomed.