I'd suggest making a webpart for it because the NodeAliasPath
will not be the correct path all the time. The simple webpart I use/create is below. The DocumentURLProvider.GetUrl()
method gets the URL with the language code, if there is one.
ASCX:
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="~/CMSWebParts/Custom/CanonicalLinks.ascx.cs" Inherits="CMSWebParts_Custom_CanonicalLinks" %>
Code behind:
using System;
using System.Web;
using System.Web.UI;
using CMS.Helpers;
using CMS.DocumentEngine;
using CMS.PortalEngine.Web.UI;
public partial class CMSWebParts_Custom_CanonicalLinks : CMSAbstractWebPart
{
public string PageExtension
{
get
{
return ValidationHelper.GetString(GetValue("PageExtension"), "");
}
set
{
SetValue("PageExtension", value);
}
}
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
if (this.StopProcessing)
{
// do nothing
}
else
{
string nodeAliasPath = DocumentContext.CurrentDocument.NodeAliasPath.ToLower();
string currentUrlPath = RequestContext.CurrentURL.ToLower();
if (nodeAliasPath != currentUrlPath)
{
this.Page.Header.Controls.Add(new LiteralControl("<link rel=\"canonical\" href=\"" + URLHelper.GetAbsoluteUrl(DocumentURLProvider.GetUrl(DocumentContext.CurrentDocument.NodeAliasPath) + PageExtension) + "\" />" + Environment.NewLine));
}
}
}
}