98374598347934875
98374598347934875

Reputation: 535

ASP.NET How to do a HTTP 301 to new domain with path and query intact

How can I do redirect all incoming requests from one domain to another and still keep the path and query?

Example from: http://domain1.com/some/path/?query to: http://domain2.com/some/path/?query.

I've been fooling around with the system.webserver in web.config, HTTP-handlers and global.asax - but without luck. I only get 404s (because the content has been moved)...

Thanks!

Upvotes: 1

Views: 994

Answers (2)

Ed B
Ed B

Reputation: 6054

You can put in a redirect in IIS & skip loading ASP.NET code all together.

In the 'HTTP redirect' section of IIS for domain1.com, set the redirect location to:

http://domain2.com/$S$Q

Then check the 'Redirect all requests to exact destination(instead of relative destination)' checkbox.

All requests including folders, files & querystring parameters will get passed to the new domain.

Edit:

Since you don't have access to IIS, you can use the Request.RawUrl method as Icarus described.

To avoid the 404 error, you can check if the page exists before you redirect:

string domain2 = "domain2.com" + Request.RawUrl;

try
{
  // *** Establish the request
  HttpWebRequest loHttp = (HttpWebRequest)WebRequest.Create(domain2);

  // *** Set properties
  loHttp.Timeout = 10000;     // 10 secs

  // Retrieve request info headers 
  HttpWebResponse loWebResponse = (HttpWebResponse)loHttp.GetResponse();

  loWebResponse.Close();

  Response.Redirect(domain2);    //Page is valid..redirect to it.
}
catch ( WebException ex )
{
  if ( ex.Status.Message.Contains("404") )    //or check that the StatusCode property is 404 or similar
     Response.Redirect("www.domain2.com"   //Redirect to front page since page doesn't exists

}

Upvotes: 0

Icarus
Icarus

Reputation: 63966

Use Request.RawUrl and replace domain1 with domain2 when you do the redirect.

From the Remarks section:

The raw URL is defined as the part of the URL following the domain information. In the URL string http://www.contoso.com/articles/recent.aspx, the raw URL is /articles/recent.aspx. The raw URL includes the query string, if present.

Update:

This:

protected void Application_BeginRequest(object sender, EventArgs e)
{
    Response.Redirect("http://www.google.com" + Request.RawUrl);
}

Definitely works as you need. You may get a 404 error but that's just because the path part of the Url does doesn't exist on domain2 (google.com on the example above). That's something you should be able to predict/correct or simply not worry. I don't know what your requirements are.

Upvotes: 2

Related Questions