Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
sitecore-alias-redirect-resolver
using Sitecore;
using Sitecore.Configuration;
using Sitecore.Diagnostics;
using Sitecore.Pipelines.HttpRequest;
using System.Net;
using System.Web;
using AliasResolver = Sitecore.Pipelines.HttpRequest.AliasResolver;
namespace LaunchSitecore.Configuration.AuthoringExperience.Processors
{
/// <summary>
/// Pipeline modification to turn Aliases into 301 redirects
/// </summary>
public class AliasRedirectResolver : AliasResolver
{
public override void Process(HttpRequestArgs args)
{
if (!Settings.AliasesActive)
{
return; // if aliases aren't active, we really shouldn't confuse whoever turned them off
}
var database = Context.Database;
if (database == null)
{
return; // similarly, if we don't have a database, we probably shouldn't try to do anything
}
var targetID = Context.Database.Aliases.GetTargetID(args.LocalPath);
// sanity checks for the item
if (targetID.IsNull)
{
Tracer.Error("An alias for \"" + args.LocalPath + "\" exists, but points to a non-existing item.");
return;
}
var item = args.GetItem(targetID);
if (database.Aliases.Exists(args.LocalPath))
{
if (item != null)
{
if (Context.Item == null)
{
Context.Item = item;
Tracer.Info(string.Concat("Using alias for \"", args.LocalPath, "\" which points to \"", item.ID, "\""));
}
HttpContext.Current.Response.RedirectLocation = item.Paths.FullPath.ToLower()
.Replace(Context.Site.StartPath.ToLower(), string.Empty);
HttpContext.Current.Response.StatusCode = (int) HttpStatusCode.MovedPermanently;
HttpContext.Current.Response.StatusDescription = "301 Moved Permanently";
HttpContext.Current.Response.End();
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment