Internal Domain Redirects with ASP.net and C# (C-sharp)

by Chris Sunday, July 19 2009

Here is nice little piece of code for issuing an internal domain redirect. Simply insert the code into the global.asax file, which should be found in the root web (www) directory. A commented line explanation is included within. ...and please excuse the improper code structuring.

In this case, we are setting up a redirect from abwebsitedesign.com to www.abwebsitedesign.com in order to ensure proper indexing by search engines.


void Application_BeginRequest(object sender, EventArgs e)
{
//if the requested domain contains this
if (HttpContext.Current.Request.Url.ToString().ToLower().Contains("http://abwebsitedesign.com"))
{
//then return this header response
HttpContext.Current.Response.Status = "301 Moved Permanently";

//and then replace the requested address with the newly defined address
HttpContext.Current.Response.AddHeader("Location", Request.Url.ToString().ToLower().Replace("http://abwebsitedesign.com", "http://www.abwebsitedesign.com"));
}



This also works nicely for telling search engines where a new page can be found (in case you change files, paths, or page names).


void Application_BeginRequest(object sender, EventArgs e)
{
//if the requested address contains this
if (HttpContext.Current.Request.Url.ToString().ToLower().Contains("http://www.abwebsitedesign.com/oldpage.aspx"))
{
//then return this header response
HttpContext.Current.Response.Status = "301 Moved Permanently";

//and then replace the requested address with the newly defined address
HttpContext.Current.Response.AddHeader("Location", Request.Url.ToString().ToLower().Replace("http://www.abwebsitedesign.com/oldpage.aspx", "http://www.abwebsitedesign.com/newpage.aspx"));
}



Pretty simple, yet very necessary for properly, and effectively maintaining SEO.

 

Tags: , , ,

ASP.net | Microsoft

Comments

Add comment


(Will show your Gravatar icon)

  Country flag

biuquote
  • Comment
  • Preview
Loading



About this Blog

This is a blog about web design and all things that are related to web design. Pertinent and relevant comments and/or questions are highly encouraged, but please be courteous and thoughtful of others whilest making comments.

If you have benefited from a post, please do the right thing and promote it. You can do this by linking to it, tweeting it, or digging it.

Thank you much.

Recent Comments

Comment RSS