Tuesday, May 31, 2016

301 redirects in a Sitecore item resolver

When migrating to Sitecore from an existing web site, one of the biggest concerns is a change in URLs - especially when it comes to search engine optimization. The common solution to this is a mix of a URL redirect module and sitemaps. However when there are a large chunk of content pages where the URL structure is changing in a common way - news articles, or blog posts for example. A Sitecore item resolver can be a good way to handle this, and by using 301 (moved permanently) is an added bonus to SEO.
using Sitecore.Configuration;
using Sitecore.Diagnostics;
using Sitecore.Links;
using Sitecore.Pipelines.HttpRequest;
using System;
using System.Web;

namespace MyProject.ItemResolvers
{
    public class MyItemResolver : HttpRequestProcessor
    {
        public override void Process(HttpRequestArgs args)
        {
            // Return if Sitecore has found the item
            if (Context.Item != null || Context.Database == null || args.Url.ItemPath.Length == 0) return;

            try
   {
    var itemPath = ""; // Business logic here to find the item based on the Context passed through
    var context = Factory.GetDatabase("web");
    var item = context.GetItem(itemPath);

    if (item != null)
    {
     var urlOptions = new UrlOptions
     {
      AlwaysIncludeServerUrl = true
     };

     var itemUrl = Sitecore.Links.LinkManager.GetItemUrl(item, urlOptions);

     HttpResponse Response = HttpContext.Current.Response;
     Response.StatusCode = 301;
     Response.StatusDescription = "Moved Permanently";
     Response.RedirectLocation = itemUrl;
     Response.Flush();
    }
   }
   catch (Exception e)
   {
    Log.Error(e.ToString(), "");
   }
        }
    }
}

Then we simply place this resolver after the default Sitecore one, which means that it will only be called if Sitecore could not find the item.
<processor type="Sitecore.Pipelines.HttpRequest.FileResolver, Sitecore.Kernel"/>
<processor type="MyProject.ItemResolvers.MyItemResolver, MyProject"/>

The only hard part is creating business logic to resolve what the item should be based on the invalid URL. Once this is done and you have found the new item, you get a legitimate 301 redirect to it.

No comments:

Post a Comment