Friday, May 15, 2015

Resolving old legacy URL’s with Sitecore


For example you need to move an old PHP website to Sitecore and you want to serve old links that user may keep in the Favorites, so when user click on xxx.com/…/some_product.php it gets sitecore Item ‘Some Product’.

  1.  Add .php extension to web.config – just find  <param desc="Allowed extensions (comma separated)"> in two places and add php extension to them.
  2. Add new Field “Old Url” to the item’s template
  3. Now we need to combine the ‘Some Product’ item ID's and OldUrl’s, you can use IDTable for example or put it to the cash.
    
    var items = SitecoreUtils.WebDb.SelectItems("fast:/../MyItems//*[@@templatename='MyItem']");   
                var dictionary = new Dictionary();
                foreach (var item in items.Where(_ => !string.IsNullOrWhiteSpace(_.Fields["OldUrl "].Value)))
                {
                    string path = new Uri(item.Fields["OldUrl"].Value) .AbsolutePath.ToLowerInvariant();
                    if (dictionary. EndsWith (path))
                    {
                        //log duplicate legacy_url value
                        Sitecore.Diagnostics.Log.Warn("In App_Start ConfigureUrlMapping: Found duplicate OldUrl value, skipping dictionary add. Item ID: " +item.ID +", URL: " +item.Fields["OldUrl "] +".", new object());
                    }
                    else
                    { 
                        dictionary.Add(path, item.ID);
                    }
                } 
    HttpRuntime.Cache.Insert("UrlMapper", dictionary);
    
    
  4. Ok, next step just to resolve .php url
    public class OldUrlResolver : HttpRequestProcessor
        {
            public override void Process(HttpRequestArgs args)
            {
                if (Sitecore.Context.Item != null) return;
                string url = args.Context.Request.Url.AbsolutePath.ToLowerInvariant();
                if (url.EndsWith(".php"))
                {
                    var items = HttpRuntime.Cache.Get("UrlMapper") as IDictionary<string, ID>;
                    if (items != null && items.ContainsKey(url))
                     {
                       Sitecore.Context.Item = items[url];
                     }
                    
                }
            }
        }
    

    Let’s register our custom processor in the web.config file
    <sitecore>
        <pipelines>
          <httpRequestBegin>
             <processor patch:after="*[@type='Sitecore.Pipelines.HttpRequest.ItemResolver, Sitecore.Kernel']" type="Pipeline.OldUrlResolver,  Pipeline" />
          </httpRequestBegin>
        </pipelines>
      </sitecore>
    
    

That is it!

No comments:

Post a Comment