Last active
August 29, 2015 14:23
-
-
Save jordanrobinson/d57f227833e59f55e505 to your computer and use it in GitHub Desktop.
sitecore-alias-redirect-resolver
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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