Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check whether Sitecore item is using alias

Currently an "Alias" in Sitecore will produce multiple routes to the same content item which can negatively affect SEO in some cases.

I am looking for a way to programatically check whether the current Page/Item/URL/Request is using an alias or not.

I was hoping there would be something along the lines of:

Sitecore.Web.WebUtil.IsAlias

Any ideas on how to check for aliases?

-------UPDATE-------

Here is my current solution which appears to work just fine... Unless anyone has a better ideas?:

protected bool IsAlias
{
    get
    {
        string fullPath = LinkManager.GetItemUrl(Sitecore.Context.Item);
        return !HttpContext.Current.Request.RawUrl.StartsWith(fullPath, StringComparison.OrdinalIgnoreCase);
    }
}

------ UPDATE 2 ------

Here is a working solution based on Yan's suggestions. I don't believe Sitecore.Context.Database.Aliases.GetTargetUrl() is working as of Sitecore 6.4.1. so I had to improvise a little.

if (Sitecore.Configuration.Settings.AliasesActive &&
    Sitecore.Context.Database.Aliases.Exists(HttpContext.Current.Request.RawUrl))
{
    const string format = "<link rel=\"canonical\" href=\"{0}://{1}{2}\"/>";
    Item targetItem = Sitecore.Context.Database.GetItem(Sitecore.Context.Database.Aliases.GetTargetID(HttpContext.Current.Request.RawUrl));
    return String.Format(format, HttpProtocol, HttpContext.Current.Request.Url.Host, LinkManager.GetItemUrl(targetItem));
}
like image 376
Derek Hunziker Avatar asked Aug 02 '11 21:08

Derek Hunziker


2 Answers

What we have done in the past is when an alias is used to set a canonical url link in the head of the page.
For example if you have /food alias pointing to /news/food when you go to the /food you'll put <link href="http://[websiteurl]/news/food" rel="canonical" /> in the <head> of the page.

EDIT:

Here is another way

public class AliasResolver : Sitecore.Pipelines.HttpRequest.AliasResolver
{
    public override void Process(HttpRequestArgs args)
    {
        base.Process(args);

        if (Context.Item != null)
        {
            args.Context.Items["CanonicalUrl"] = Context.Item.GetFullUrl(args.Context.Request.Url);
        }
    }
}

Then in your header control all you need to do is check whether HttpContext.Current.Items["CanonicalUrl"] is set and display it.

like image 77
marto Avatar answered Nov 17 '22 00:11

marto


I would rely on the Context.Database.Aliases.Exists(path) in your case. Also, it seems to be a good idea to check whether the aliases are active in the web.config: Sitecore.Configuration.Settings.AliasesActive.

like image 20
Yan Sklyarenko Avatar answered Nov 16 '22 23:11

Yan Sklyarenko