Posted in: Comments

One really big enhancement is canonical urls for your/customers content. I’m sure you all know about the problem with duplicated content, but not everyone tend to fix it. Here’s my take on it.

namespace DV.HttpModules
{
    using System;
    using System.Web;

    public class CanonicalDomainModule : IHttpModule
    {
        public delegate void CanonicalDomainEventHandler(UriBuilder url);

        public static event CanonicalDomainEventHandler BeforeChangingDomain;
        public static event CanonicalDomainEventHandler AfterChangingDomain;

        void IHttpModule.Dispose()
        {

        }

        void IHttpModule.Init(HttpApplication context)
        {
            context.BeginRequest += new EventHandler(this.RedirectDomains);
        }

        private void RedirectDomains(object sender, EventArgs e)
        {
            HttpApplication application = sender as HttpApplication;
            UriBuilder requestedUrl = new UriBuilder(application.Context.Request.Url);

            string siteHost = EPiServer.Configuration.Settings.Instance.SiteUrl.Host;

            if (!requestedUrl.Host.Equals(siteHost, StringComparison.OrdinalIgnoreCase))
            {
                if (BeforeChangingDomain != null)
                {
                    BeforeChangingDomain(requestedUrl);
                }

                requestedUrl.Host = siteHost;

                if (AfterChangingDomain != null)
                {
                    AfterChangingDomain(requestedUrl);
                }

                string location = requestedUrl.Uri.GetComponents(
                    UriComponents.Scheme |
                    UriComponents.Host |
                    UriComponents.Path |
                    UriComponents.Query |
                    UriComponents.Fragment,
                    UriFormat.Unescaped);

                this.PermanentRedirect(application, location);
            }
        }

        private void PermanentRedirect(HttpApplication application, string location)
        {
            application.Context.Response.Clear();
            application.Context.Response.Status = "301 Moved Permanently";
            application.Context.Response.AddHeader("Location", location);
            application.Context.Response.End();
        }
    }
}

Modules are executed in the order they are configured. So if we register it before EPiServer’s UrlRewriteModule the url will not be rewritten when the module is executed, not a big deal in this case, but just remember it.