Sitecore with SXA is really easy and simple to work with redirects. When you have a product, ring as example, it has multiples carat weight so you create 3 variants.
You can use as base template SXA redirect item /sitecore/templates/Feature/Experience Accelerator/Redirects/Redirect with that you can see on screen Redirect Url section:
We can define on “Nicky Ring” product the redirect URL to Carat weight 070. It will work good. But we have a different scenario, I need to redirect to this product when I type on Url http://mysite.com/products?ref=REF12354 as “ref” my Reference number on Sitecore product item.
How can I do that? Don’t worry we will take over bellow.
First you need to create a Custom Pipeline on your config file in Visual Studio Solution:
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
<sitecore>
<pipelines>
<httpRequestBegin>
<processor patch:after="processor[@type='Sitecore.Pipelines.HttpRequest.ItemResolver, Sitecore.Kernel']" type="MyProject.Foundation.SitecoreExtensions.ItemResolver.ItemResolver, MyProject.Foundation.SitecoreExtensions" />
</httpRequestBegin>
</pipelines>
</sitecore>
</configuration>
After that you create your class:
public class ItemResolver : HttpRequestProcessor
{
public override void Process(HttpRequestArgs args)
{
}
}
When you have your class so now it’s the most fun part that I love.. Implement our code.
On this example, I’m getting url, verifying my parameter “ref=”.
If exits, I will do my Sitecore Query to get this item. After that we have to check if item is not null to get item url, otherwise we redirect to site homepage.
var url = HttpContext.Current.Request.Url.AbsoluteUri;
if (url.Contains("ref="))
{
var myUri = new Uri(url);
try
{
var refParam = HttpUtility.ParseQueryString(myUri.Query).Get("ref");
var sitecoreUrlItem = SitecoreUrlItem(refParam);
if (!string.IsNullOrEmpty(sitecoreUrlItem))
args.HttpContext.Response.RedirectPermanent(sitecoreUrlItem);
}
catch (Exception)
{
}
}
private string SitecoreUrlItem(string refNumber)
{
var url = string.Empty;
try
{
var sitecoreDB = Sitecore.Context.Database;
var sitecoreQuery = $"/sitecore/content/MySite/Home/Products//*[@ReferenceNumber ='{refNumber}']";
var prodItem = sitecoreDB.SelectSingleItem(sitecoreQuery);
if(prodItem != null)
{
url = LinkManager.GetItemUrl(prodItem);
}
else
{
var homeItem = Sitecore.Context.Database.GetItem(Sitecore.Context.Site.StartPath);
url = LinkManager.GetItemUrl(homeItem);
}
}
catch (Exception ex)
{
Sitecore.Diagnostics.Log.Error($"Error to Redirect to product with ReferenceNumber:{refNumber}", ex.Message);
}
return url;
}
It’s done! With that you have your custom Redirect url to specific item.
If you have any question or any suggestion, leave your comment or send me an email!
Peace!