BlogEngine - Extension for canonical tags

Now something different - as we use BlogEngine.io for our blog system we experienced issue that this Blog software does not add canonical tags which are needed for SEO.

Now, extension is not that complicated (btw. we use 3.3.6 version).

Search for file account.master and add there in <head> section:

 <link href="https://YOUR_URL/account/login.aspx" rel="canonical" />

As a second step go to BlogEngine.Core project and search for file BlogBasePage.cs (should be in \Web\Controls folder) and add following code (I put it after protected virtual void AddMetaContentType()):

      /// <summary>
        /// Adds the canonical tag to the header.
        /// </summary>
        protected virtual void AddCanonical()
        {
            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;
        }
 
In case that you want to add canonical tag only to post pages uncomment
 
if (rawUrl.Contains("/post/"))
 
and in case that you have QueryStrings you'll need to uncomment
 
bool hasQueryStrings = Request.QueryString.Keys.Count > 1;
and
if (hasQueryStrings)
 
 
Hope that this helps.
Comments are closed