How to add URL Rewrites programmatically in Magento 2

Image result for magento 2


In this blog, we discuss about URL Rewrites programmatically in magento 2, it is the best solutions for online vendors as you who desire to truly build a huge number of the traffics of your websites. The function of rewrite the URL is allowing you producing 301 redirects in to Magento 2 by programmatically.

URL redirect

URL redirect is a major term in SEO and it is used for navigating the visitors to any link store owners expect. There are two main type of redirect

  • 301 redirect
  • 302 redirect

Therefore, if you are wondering how to maintain working with the existing visitor at the current site while you are planning to make a new site with more efficiencies, creating the search redirection through the redirect 301 is the best answer.

The below mentioned steps help you to add URL Rewrites programmatically in Magento 2

Step 1: Create constructor file

Step 2: Construct custom URL rewrite in execute method

Create constructor file


* @var \Magento\UrlRewrite\Model\ResourceModel\UrlRewriteFactory


protected $_urlRewriteFactory;


* @param Context $context

* @param \Magento\UrlRewrite\Model\ResourceModel\UrlRewriteFactory $urlRewriteFactory


ublic function __construct(

    Context $context,

    \Magento\UrlRewrite\Model\ResourceModel\UrlRewriteFactory $urlRewriteFactory

) {

    $this->_eavAttributeFactory = $eavAttributeFactory;





 Construct custom URL rewrite in execute method

The definite website URL is, but you want to execute the URL as URL) then you can build by the following method:

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

/* set current store id */


/* the following url is not formed by system so set as 0 */


/* unique identifier - place random unique value to id path */

$urlRewriteModel->setIdPath(rand(1, 100000));

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


/* set requested path which you desire to form */


/* set current store id */


I hope, these steps help you to add URL Rewrites programmatically in Magento 2

Last Update: October 31, 2019  

February 20, 2018   6811   Nandini Ramachandran    Magento    
Total 6 Votes:

Tell us how can we improve this post?

+ = Verify Human or Spambot ?


Leave a Reply

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