Improving SEO With ASP.Net MVC - Part 2 - SEO Tags

Improving SEO With ASP.Net MVC - Part 3 - Google Search Features

The Problem

When Google crawls your website looking for links to index, it sees each variation of a link as a unique link. A link that includes www. is not the same as a link that doesn't. The same holds true for uppercase and lower case URLs. Although your website will still render the page because ASP.Net can handle both uppercase and lowercase URLs it's not recommended to get the best SEO possible for your site. You also want to insure that you are not creating duplicate urls with http:// and https://. Google will see those as two separate URLs and split the SEO value across both.

The Solution

Step 1 - Find your global.asax

This should be located in your main solution directory.

Step 2 - Change or Add Applicaton_BeginRequest function

We are going to add three sections of code inside the Application_BeginRequest that will convert all http:// URLs to https:// URLs, convert all non www URLs to www URLs and lowercase the entire URL that way we are truly only creating one URL to be indexed by all the major search engines. If you're site is not SSL secured please skip the HTTPs section.

The benefit to putting all of this in the Application_BeginRequest is that even if somebody creates a link to your website externally, when that link is clicked on the URL will do a 301 redirect telling all systems that it's a permanent redirect. Having it in the Application_BeginRquest will also catch any mistakes you make throughout your code with uppercase and lowercase urls.

protected void Application_BeginRequest(object sender, EventArgs e)
        {
            if (!HttpContext.Current.Request.IsLocal && !HttpContext.Current.Request.Url.Host.StartsWith("www"))
            {
                var Builder = new UriBuilder(Request.Url);
                Builder.Host = "www." + Request.Url.Host;
                Response.RedirectPermanent(Builder.ToString(), true);
            }
            if (HttpContext.Current.Request.IsSecureConnection == false && HttpContext.Current.Request.IsLocal == false)
            {
                Response.RedirectPermanent("https://" + Request.ServerVariables["HTTP_HOST"] + HttpContext.Current.Request.RawUrl);
            }
            var url = Request.Url.ToString();
            if (Regex.IsMatch(url, @"[A-Z]") && Request.HttpMethod != "POST" && !url.Contains("Bundles"))
            {
                Response.Clear();
                Response.Status = "301 Moved Permanently";
                Response.StatusCode = (int)HttpStatusCode.MovedPermanently;
                Response.AddHeader("Location", url.ToLower());
                Response.End();
            }
        }

Improving SEO with ASP.net MVC - Part 2