How to Add Magento 2 URL Rewrite Programmatically?

How to Add Magento 2 URL Rewrite Programmatically?
Restore Canceled Order M2
4.8
5 Reviews

Streamline order management and avoid sales losses due to accidental order cancellation or change of mind. The Magento 2 Restore Canceled Order extension helps you recover orders that you have canceled by mistake or were requested by an indecisive customer.

$89.99

Cache Warmer M2
5.0
4 Reviews

Significantly reduce page load times and improve customer browsing experience using Magento 2 Cache Warmer. Pre-generate cache and Warm pages in advance so that they are readily served when requested.

$79.99

Restrict Fake Registration M2
5.0
2 Reviews

Prevent fake registrations to safeguard your online store’s integrity and security. With the Magento 2 Restrict Fake Registration extension, you can restrict registrations based on email domains, IP addresses, special characters, and character limits for first, middle, and last names.

$59.99

Delete Account M2
5.0
3 Reviews

Make your store GDPR compliant by giving your customers the option to permanently delete their accounts. The Magento 2 delete customer account extension allows customers to submit account deletion requests to the store administrator and receive an email notification upon account deletion.

$59.99

SMTP M2
5.0
1 Review

Enhance your email communication with the Magento 2 SMTP extension. Effortlessly setup a trusted Simple Mail Transfer Protocol (SMTP) server on your Magento 2 store and reduce the risk of your emails being marked as spam.

$49.99

Minimum Order Amount For Customer Group M2
5.0
3 Reviews

Segment your pricing strategy for different customer groups and increase your profit margins. The Magento 2 minimum order amount for customer group extension allows you to set different minimum order requirements by customer groups and display a message if the requirement is not met.

$49.99

One of the most powerful and widely acclaimed Magento features is the URL rewrite. This article discusses everything there is to know about URL rewrite, including what it is, benefits, and Magento 2 URL rewrite programmatically.

What Is URL Rewriting?

URL rewriting is the process of making your entire store URLs uniform for the purposes of better user readability and search engine friendliness. It makes URLs easier to remember, meaningful, keyword-rich, and easier to index.

Consider the following 3 URLs:

  • http://www.abc.com/show_a_product.php?product_id=3

This URL is too long not just from the reader’s perspective but also the web crawlers. It means that it will be difficult to index and rank this page. On top of it, it contains no keyword at all.

  • http://www.abc.com/products/3/

The above URL is much more concise. We can easily discern that the URL is about a product what we cannot know for sure which product it is, nor is there a keyword.

  • http://www.abc.com/bags/overnight-duffle/

Now, this URL is much more meaningful. The user and the web crawlers can easily determine what the webpage is about – Nike duffle bags. The URL also contains the keyword, making it easier to rank in the search engine results pages.

URL rewriting is used to create URLs like the last one and tell servers how to process them.

import-export-url-rewrites

Import Export URL Rewrites

Boost SEO and manage URLs easily with the Magento 2 URL Rewrites Import-Export extension. Add, replace, or delete URL rewrites in bulk efficiently.

Benefits of Magento 2 URL Rewrites

Search Engine Optimisation

Web crawlers can easily read clean and friendly URLs, thereby improving the webpage’s ranking in results pages.

User Experience

Clean URLs are easy to remember and view from a user’s perspective, thereby enhancing their overall experience. The store benefits from repeat visits which can contribute to higher conversions.

Branding

Lastly, URL rewrites help the store ensure consistency in URL practices. This can prove beneficial from a branding perspective.

What is the Need to Add URL Rewrite Programmatically?

You can add URL rewrite manually if you have a few URLs. But this is usually not the case if you have an ecommerce store. You may have tens of categories, subcategories and hundreds of products and CMS pages. Adding URL rewrite for all these pages is a near impossible task. The best way is to do it programmatically.

Magento 2 URL Rewrite Programmatically

The URL Rewrite tool lets you change any URL that is associated with a product, category, or CMS page. When the rewrite goes into effect, any links that point to the previous URL are redirected to the new address. Follow the steps below to enable URL rewrite programmatically in Magento 2.

Step 1: Generate a Constructor File

<?php 
/**
 * @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: Fill in Custom URL Rewrite in Execute 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");

/* save URL rewrite rule */
$urlRewriteModel->save();

Using a Magento 2 URL Rewrite Extension

Our Magento 2 URL Rewrite Extension makes URL rewriting much easier and more user-friendly. It offers a wide range of features, including:

  • Add, merge, replace, or delete existing URL rewrites
  • Create Export Profiles
  • View Export History
  • Export URL Rewrites Based on Different Variables (e.g. store view, redirects)
Related Extensions:

Final Thoughts on Magento 2 URL Rewrite Programmatically

That’s all about adding URL rewrite programmatically in Magento 2. Any questions or comments regarding URL rewrites in Magento 2 are welcomed.

Related Articles:

This blog was created with FME's SEO-friendly blog