Magento2 Programmatically Create Custom URL Rewrites – 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 I am going to explain the process to create custom URL using code in controller file.
Step 1 : Create 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; parent::__construct( $context ); }
Step 2 : Create custom URL rewrite in execute method.
Like your website actual URL is www.example.com/customModule/customController/customAction but you want to execute this URL on click on www.example.com/xyz (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("www.example.com/customModule/customController/customAction"); /* set requested path which you want to create */ $urlRewriteModel->setRequestPath("www.example.com/xyz"); /* set current store id */ $urlRewriteModel->save();
So in this way you can create custom URL. Thanks!