Adding The Canonical Tag To Reference Original URLs

Jul 27, 2009 at 2:01 PM
Edited Jul 28, 2009 at 4:42 AM

Has anyone found a way to include a canonical tag that references the original posts so that URLs like www.website.com/post/2009/07/26/example.aspx?utm_source=twitter&utm_medium=social-media don't get indexed by search engines?

Now, I know how to add the tag programmatically:


        HtmlLink canonicalTag = new HtmlLink();
        canonicalTag.Href = "http://www.website.com/post/2009/07/26/example.aspx";
        canonicalTag.Attributes["rel"] = "canonical";
        Page.Header.Controls.Add(canonicalTag);

 

But, what would be the way to insert the canonical URL on each page that needs it?

Jul 28, 2009 at 4:07 AM

After much labor, we have created the follow code to be added to the site.master.cs.

This basically checks to see if "/post/" is in the URL, if so, then it checks to see if there are any query strings. If there are query strings, then it inserts the canonical tag with a link to the correct "canonical" location.

I have omitted the code that is already in site.master.cs (version 1.5).

 

public partial class StandardSite : System.Web.UI.MasterPage
{
protected void Page_Load(object sender, EventArgs e)
{

string rawUrl = String.Concat(this.GetApplicationUrl(), Request.RawUrl);

        if (rawUrl.Contains("/post/"))
        {
            bool hasQueryStrings = Request.QueryString.Keys.Count > 1;

            if (hasQueryStrings)
            {
                Uri uri = new Uri(rawUrl);
                rawUrl = uri.GetLeftPart(UriPartial.Path);

                HtmlLink canonical = new HtmlLink();
                canonical.Href = rawUrl;
                canonical.Attributes["rel"] = "canonical";
                Page.Header.Controls.Add(canonical);
            }
        }

}

    private string GetApplicationUrl()
    {
        string basePath;
        string port = HttpContext.Current.Request.ServerVariables["SERVER_PORT"];
        string protocol = HttpContext.Current.Request.ServerVariables["SERVER_PORT_SECURE"];
        string serverName = HttpContext.Current.Request.ServerVariables["SERVER_NAME"];

        if (port == null || port == "80")
        {
            port = String.Empty;
        }
        else
        {
            port = String.Concat(":", port);
        }

        if (protocol == null || protocol == "0")
        {
            protocol = "http://";
        }
        else
        {
            protocol = "https://";
        }

        basePath = String.Concat(protocol, serverName, port);
        return basePath;
    }
}


Very useful, and works flawlessly. Enjoy!