Using IHttpModule to url-rewrite.


A ThatsIT Solutions Tutorial

Here I will show you how rewrite occurrences of "seo-perth" to seoperth, and 301 redirect "seoperth" to "seo-perth" using the IHttpModule class.

For instuctions on creating the IHttpModule class. Please refere to Using IHttpModule, Visual Basic or Using IHttpModule, C-Sharp.

Visual Basic
Dim application As HttpApplication = DirectCast(source,  _
       HttpApplication)

   Dim context As HttpContext = application.Context
   Dim origionalpath As String = LCase(context.Request.Url.PathAndQuery)
   Dim newPath As String = String.Empty

   Const seoPerthA As String = "seo-perth"
   Const seoPerthB As String = "seoperth"

   If origionalpath.Contains(seoPerthA) Then
	newPath = Replace(origionalpath, seoPerthA, seoPerthB, 1, 1)
	context.RewritePath(newPath)
   End If

   If origionalpath.Contains(seoPerthB) Then
	newPath = Replace(origionalpath, seoPerthB, seoPerthA)
	context.Response.Status = "301 Moved Permanently"
	context.Response.AddHeader("Location", _
	String.Format("{0}://{1}{2}", _
	context.Request.Url.Scheme, context.Request.Url.Host, newPath))
   End If
C-Sharp
HttpApplication application = (HttpApplication)source;
   HttpContext context = application.Context;

   String origionalpath  = context.Request.Url.PathAndQuery.ToLower();
   String newPath = string.Empty;

   const string seoPerthA = "seo-perth";
   const string seoPerthB = "seoperth";

   if(origionalpath.Contains(seoPerthA)){
	newPath = origionalpath.Replace(seoPerthA, seoPerthB);
        context.RewritePath(newPath);
   }

   if(origionalpath.Contains(seoPerthB)){
	newPath = origionalpath.Replace( seoPerthB, seoPerthA);
        context.Response.Status = "301 Moved Permanently";
        context.Response.AddHeader("Location", 
	String.Format("{0}://{1}{2}", 
	Context.Request.Url.Scheme, context.Request.Url.Host, newPath));
   }