The term URL rewrite is important in SEO, as it makes URLs meaningful and readable. For example, you want to redirect your customers to particular Product/category Pages, URL of that pages is like http://www.xyz.com/catalog_id/?id=3 then the customer can not reach that Product/Category pages.
For that, you need to make such a URL that customers can easily reach. Like http://www.xyz.com/dash-digital-watch, Now, customers and search engines both can easily get to your Product/Category pages.
- To generate the constructor, you have to use below block of code in your controller file: Here, we have used Magento\UrlRewrite\Model\UrlRewriteFactory instance and created its object($urlRewriteFactory).
- In execute method, create URL rewrite factory.
- Set Entity Type as you rewrite URL is custom URL or CMS page or category page or product page, then set store ID in which you want to rewrite URL.
- Set 0 to the setIsSystem() as URL is not created by the system.
- We have set the random unique value to the ID path. Then set Target Path and Requested Path.
- After that, set Redirect Type. 301 is for Permanent redirect and 302 is for Temporary Redirect.
- That's How you can rewrite the URL and navigate the customer to the link you want.
<?php namespace Vendor\Module\Controller; use Magento\Framework\App\Action\Context; class YourController { /** * @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); } public function execute() { $urlRewriteModel = $this→_urlRewriteFactory→create(); /*set entity type you if you want to rewrite url for “custom”, “for cms page”, “for product”,“for category” */ $urlRewriteModel→setEntityType('custom'); /*for set current store ID */ $urlRewriteModel→setStoreId(1); /*set 0 as this url is not created by system */ $urlRewriteModel→setIsSystem(0); /* unique identifier - place random unique value to ID path */ $urlRewriteModel→setIdPath(rand(1, 100000)); /* set actual url path to target path field */ $urlRewriteModel→setTargetPath(‘target-url.html’); /* set requested path which you want to create */ $urlRewriteModel→setRequestPath(‘requested-url.html’); /*set Redirect type*/ $urlRewriteModel→setRedirectType(301); /* save URL rewrite rule */ $urlRewriteModel→save(); } } |
Conclusion :
We hope above blog helps you to clearly understand How to rewrite URL Programmatically in Magento 2.
In case of any kind of problem with the above code implementation, you can contact us or let us know in comment section. Thank You!