简体   繁体   中英

How can I redirect a URL to change the host part only in aspx?

I want to redirect one site to another site in a way that other parts of URL remain unchanged. For example: http://abc.com/test1/doc1.aspx redirects to http://xyz.com/test1/doc1.aspx

Thanks, Ali

Replace the host from the first url with the expected new host as shown below

string currentUrl = "http://abc.com/test1/doc1.aspx";
Uri uri = new Uri(currentUrl);

//Result: "http://xyz.com/test1/doc1.aspx"
string newUrl = currentUrl.Replace(uri.Host, "xyz.com");
Response.Redirect(newUrl);

Better idea is to change DNS records if possible in order to avoid excessive redirects.

If you really want to redirect everything just add this to your web.config in the root folder

<configuration>
    <system.webServer>
         <httpRedirect enabled="true" destination="http://xyz.com" httpResponseStatus="Permanent" />
    </system.webServer>
</configuration>

You transform a URI like this:

private RedirectToNewHost( Uri uri , string newHost )
{
  UriBuilder builder = new UriBuilder( uri ) ;
  builder.Host = newHost ;
  Response.Redirect(builder.Uri.AbsoluteUri);
}

private RedirectToNewHost( string uri , string newHost )
{
  UriBuilder builder = new UriBuilder( uri ) ;
  builder.Host = newHost ;
  Response.Redirect( builder.Uri.AbsoluteUri );
}

But as @Dragan_Radivojevic pointed out, modifying DNS so that the old domain name is an alias for the new domain is a clean solution. Then, if you've changing domain names, have the web server look at the inbound URI and pop up an informative message that the domain name has changed and they should start using the new domain name.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM