Introduction
When using HttpModules to re-write URLs, accessing a directory will not work. For example, a request to http://somewebsite/fakedirectory/ will not work unless the fakedirectory actually exists with some default index file in it. This occurs because when a request comes into IIS it first ascertains that the directory and file actually exist before ever instantiating the HttpModule in your ASP.NET application.
Solution
Solving this is actually fairly easy. The first thing to do is to load IIS and change the 404 errors to a URL destination and point it to your site.
This will tell IIS to automatically redirect any unknown request (e.g. to a directory that does not exist) to your application. When you do this your application will receive a request like the following: http://somewebsite/default.aspx?404;http://somewebsite/fakedirectory/
Using the Code
Because this is in a standard form, the HttpModule can parse this easily, extract the real website that the user wanted and then perform the standard rewrite.
internal static String GetRequestedURL(String originalRequest)
{
String url = originalRequest;
if (url.Contains(";") && url.Contains("404"))
{
String[] splitUrl = url.Split(';');
if (splitUrl.Length >= 1)
{
url = splitUrl[1];
url = url.Replace("http://", "");
int index = url.IndexOf(
System.Web.HttpContext.Current.Request.ApplicationPath);
if (index >= 0)
{
url = url.Substring(index);
}
}
}
return url;
}
The GetRequestURL
function will take a RawURL parameter and then check if it is a 404 error. If it is, it will parse out the original request and return it. If it is not a 404 error then it will return the untouched RawURL.
Concluding Remarks
While this is a fairly simple answer, I have been looking everywhere for a solution and nobody seems to have an easy answer. Even using the HttpHandler will not solve the problem because there's no extension on the requests for a directory. This is the best solution I have found and it works every time without having to do any extensive changes.
History
- April 03, 2007 - Created
- April 11, 2007 - Modified to take into account root applications