Write Yourself a Merry Little URL Re-writer
3 Comments Published by boris August 21st, 2009 in technology, umbraco, web developmentA common web development concern is the www subdomain. Do you host at http://www.site.com or http://site.com? Which ever you choose you want to be sure that visitors who type in the other get re-directed properly.
If you use IIS you can setup a new website to do such a permanent redirect, but that solution doesn’t scale well. For example, we run 42 websites using one install of umbraco, and consequently one IIS website. We’d need 42 new websites in IIS to use the built-in redirect feature.
One example site is http://en.culturalcare.com, and I want to make sure that if someone types in http://www.en.culturalcare.com they get redirected properly. The solution is to write a little generic URL re-writer yourself using the global.asax file.
< %@ Application Language="C#" %> <script runat="server"> protected void Application_BeginRequest(Object sender, EventArgs e) { string domainName = Request.Url.Host.Replace("www.", "").ToLower(); string sOldPath = HttpContext.Current.Request.Path.ToLower(); string sPage = "http://" + domainName + sOldPath; Response.Clear(); Response.Status = "301 Moved Permanently"; Response.AddHeader("Location",sPage); Response.End(); } </script> |
As you can see the code removes “www.” from the url and 301 redirects to the non-www version. It also passes the full path.
You could modify the code slightly to add www’s instead of removing them if that’s the desired effect:
< %@ Application Language="C#" %> <script runat="server"> protected void Application_BeginRequest(Object sender, EventArgs e) { string domainName = Request.Url.Host.ToLower(); string sOldPath = HttpContext.Current.Request.Path.ToLower(); string sPage = "http://www." + domainName + sOldPath; Response.Clear(); Response.Status = "301 Moved Permanently"; Response.AddHeader("Location",sPage); Response.End(); } </script> |
Download a full example for use with IIS.
To implement:
- create a new site in IIS and add host headers for all of the domains you would like to redirect
- extract the zip above to the directory setup in IIS
- setup wildcard application mapping in IIS to let the global.asax file handle all requests (not just ones that end in .aspx, etc). On windows server 2003 just go to Home Directory -> Configuration and paste in the aspnet_isapi.dll location in the wildcard application maps section. By default the path is C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll (uncheck “Verify that file exists”)