Wednesday, April 13, 2011

Adding 301 Redirection to sitecore aliasing

Working with Sitecore aliases had turned to be a somewhat lacking experience. They are mostly used as short urls to a content item. When using aliasing, the pages are not redirect to the original item but just assign the context item to the original item leaving the Url to be of the alias. This creates a big problem for SEO of content duplication.
I have replaced the original AliasResolver with one that redirects with a 301 header which solves the problem.


Create a new class with the original AliasResolver code and replace the "ProcessItem" method with the following:

private bool ProcessItem(HttpRequestArgs args)
{
  ID targetID = Context.Database.Aliases.GetTargetID(args.LocalPath);
  if (!targetID.IsNull)
  {
     Item item = args.GetItem(targetID);
     if (item != null)
     {
           HttpContext.Current.Response.RedirectLocation = item.Paths.FullPath.ToLower().Replace(Context.Site.StartPath.ToLower(), string.Empty);               
           HttpContext.Current.Response.StatusCode = 301;
           HttpContext.Current.Response.Status = "301 Moved Permanently";
           HttpContext.Current.Response.End();
      }
      return true;
   }
  Tracer.Error("An alias for \"" + args.LocalPath + "\" exists, but points to a non-existing item.");
   return false;
}
In the web.config:

Replace

<processor type="Sitecore.Pipelines.HttpRequest.AliasResolver, Sitecore.Kernel"/>

With the reference to your new class.

3 comments:

  1. where do you get the original AliasResolver code from? I only have the compiled dlls

    ReplyDelete
  2. We provide growth for both nyetablerede- and major Danish companies who want to exploit the potential of online marketing for the lowest possible price. Read it on issue.

    ReplyDelete