Page canonicals

Kurt Muller asked on August 8, 2018 16:07

Hi guys

I've seen many variations of this question been answered but nothing that resolves my issue:

I see some common practices where people use {%CurrentDocument.AbsoluteURL%} to pull in the canonical, but this only seems to work if you're either setting up a one domain site or your cultures are configured to make use of language prefixes and not to force the domain culture.

I'd like to get a canonical that gives me both the page path together with it's current culture domain alias.

Is this at all possible?

Thanks Kurt

Recent Answers


Brenden Kehren answered on August 8, 2018 17:27

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));

            }
        }
    }
}
0 votesVote for this answer Mark as a Correct answer

   Please, sign in to be able to submit a new answer.