Apparently, if your site is built with ASP .NET and you have some canonical rewriting to do, ISAPI_rewrite is the total what’s cool. Convenient .htaccess and full RegEx support, nice.
Unless you happen to not have any access to your host server to install ISAPI. I found myself in this situation and thought I would share my solution. As an added perk to taking this route — you don’t have to specify everything to be redirected, you can simply specify the canonical version and any request that doesn’t match gets 301′d auto-mati-cally. Cool (especially for the lazy).
Heed my advice at your own risk — I have a notorious reputation for dropping sites. This worked for me, but there’s no guarantee it won’t mess something up in every situation.
Assuming you have file-level access to your site and the code is in C# (a VB translation shouldn’t be too hard, but I’m not gonna do it)…
1)Find Global.asax and open it for editing
2)Find the Application_BeginRequest Event (it should be right there at the beginning, all the next steps are code to be nested within this event. Here’s what mine looks like:
<script RunAt="server">
protected void Application_BeginRequest(Object sender, EventArgs e)
{
3) First, set the variables to work with:
string page = Request.Path.ToString();
string host = Request.Url.Host.ToString();
One of the (few) cool things I’ve found about ASP .NET is that the request is pre “parsed” into very usable segments. The “Request.Path” object returns everything after the host (/thepage.aspx) — Request.Url.Host is just what it sounds like — the host portion of the request URL (www.thewebsite.com)
4)If there are any requests to keep un-redirected — subdomains for example — we’ll first have to exclude those. Let’s say we have a blog subdomain for this example, we’ll start the code by excluding it from the redirect. We also have to exclude the canonical host from the request as well (I’ve nested my ifs for display):
if (host != "blog.thewebsite.com")
{
if (host != "www.thewebsite.com")
5. The redirect. Notice that I’m not using Response.Redirect — that’s because it returns a 302. I haven’t found native support for automatic 301s, hence the following:
{
Response.Clear();
Response.Status = "301 Moved Permanently";
Response.AddHeader("Location", "http://www.website.com" + page);
Response.End();
}
}
Done and done. The whole thing put together looks like:
protected void Application_BeginRequest(Object sender, EventArgs e)
{
string page = Request.Path.ToString();
string host = Request.Url.Host.ToString();
if (host != "blog.thewebsite.com")
{
if (host != "www.thewebsite.com")
{
Response.Clear();
Response.Status = "301 Moved Permanently";
Response.AddHeader("Location", "http://www.thewebsite.com" + page);
Response.End();
}
}
}