Here’s a quick draft on how to create URL Rewrites in Magento 2:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
/** * @var \Magento\UrlRewrite\Model\UrlRewriteFactory */ protected $urlRewriteFactory; /** * @var int */ protected $storeId = 1; /** * Redirects constructor. * @param \Magento\UrlRewrite\Model\UrlRewriteFactory $urlRewriteFactory */ public function __construct( \Magento\UrlRewrite\Model\UrlRewriteFactory $urlRewriteFactory ) { $this->urlRewriteFactory = $urlRewriteFactory; } /** * @param string $oldUrl * @param string $newUrl */ public function createRewrite(string $oldUrl, string $newUrl) { $urlRewrite = $this->urlRewriteFactory->create(); $urlRewrite->addData( [ 'entity_type' => \Magento\UrlRewrite\Controller\Adminhtml\Url\Rewrite::ENTITY_TYPE_CUSTOM, 'entity_id' => 0, 'request_path' => $oldUrl, 'target_path' => $newUrl, 'redirect_type' => \Magento\UrlRewrite\Model\OptionProvider::PERMANENT, 'store_id' => $this->storeId, 'description' => null, 'is_autogenerated' => 0, 'metadata' => null ] ); $urlRewrite->getResource()->save($urlRewrite); } |
Visitors give this article an average rating of 2.0 out of 5.
How would you rate this article?
★ ★ ★ ★ ★
Its works perfectly !!! Much Appreciated your efforts !! Thanks for the wonderful tutorial.
Useful Article! Thanks for sharing this step by step guide. Well, during my research I have found tutorial on enabling URL Rewrite in Magento 2: https://magenticians.com/magento-2-url-rewrite/
Hope it will help others also 🙂
Thank you.