Redirect Single Pages with ASP.NET

The Goal

I recently had to redirect an old website to a new domain. The old domain had 11 pages indexed by Google but I only needed them to redirect to the home page of the new domain, rather than all having separate redirects to new URLs.

If I were using Apache this type of redirect would be easy to implement with a .htaccess rewrite rule. Therefore, I expected that Microsoft’s IIS web server would have a similar scripting method to redirect a whole website to a new domain.

(This was a shared hosting account so access to the IIS sever itself was not possible.)

What Doesn’t Work

First I tried playing with the global.asa file, as I knew that it could be used to control page access. However, it appears that it will only work for files that actually exist, and seeing as I had deleted the old unwated files from the web server, global.asa got me nowhere!

Resigned to the fact that I would have to upload copies of the 11 files again, I also tried some classical ASP redirect code that I had used previously to redirect pages. That code didn’t work, either, and resulted in a 500 Internal Server Error.

The Solution

Let me just point out that I’m not an ASP programmer, but I have no idea why it was so difficult to find some simple ASP.NET code to redirect a single page to another.

For anyone who needs it, the following code should be placed inside your .aspx file and will redirect to the new URL with a 301 status code (best practice for SEO):

<%@ Page Language="C#" %>
<script runat="server">
  protected override void OnLoad(EventArgs e)
  {
      Response.Status = "301 Moved Permanently";
      Response.AddHeader("Location","http://www.example.com");
      base.OnLoad(e);
  }
</script>

One Comment

  1. Barnaby Knowles

    The problem with Response.Redirect() is that is uses an HTTP status code of 302 (“Moved Temporarily”). I needed to use a 301 status code (“Moved Permanently”) to tell search engines to use the new domain.

Comments are closed.