Magento 2 Add URL Rewrite Programmatically

URL rewrite is one of the best solutions for e-commerce website if you really want to create a huge number of the traffic in your website. The purpose of rewriting the url is allowing you to generate 301 redirects in the programmatic way.

What is URL Redirect?

It is the popular term in SEO and it is used for navigating the visitors to any link which store owners wants. There are two main type of redirect: 301 redirect and 302 redirect.

For normal users, there is a common need of custom URLs for controlling their websites and they can create their custom URLs using magento2 URL rewrite features, but if you want to create custom URLs programmatically then the solution is here. Here we will explain the process to create custom URL using code in controller file.

Overview of Magento 2 URL Rewrite programmatically

Step 1 : Generate constructor file

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

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

Step 2 : Create custom URL rewrite in execute method

Like your website actual URL is {baseurl}/module_name/controller_name/action_name but you want to execute this URL on click on {baseurl}/data (requested URL) then you can create by following 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("http://www.abcxyz.com/module_name/controller_name/action_name");
/* set requested path which you want to create */
$urlRewriteModel->setRequestPath("http://www.abcxyz.com/data");
/* set current store id */
$urlRewriteModel->save();

Leave a Reply