【问题标题】:ASP.NET How to do a HTTP 301 to new domain with path and query intactASP.NET 如何使用完整的路径和查询对新域执行 HTTP 301
【发布时间】:2011-11-30 21:50:47
【问题描述】:

如何将来自一个域的所有传入请求重定向到另一个域并仍然保留路径和查询?

示例 从:http://domain1.com/some/path/?query 到:http://domain2.com/some/path/?query

我一直在使用 web.config、HTTP-handlers 和 global.asax 中的 system.webserver - 但没有运气。我只得到404(因为内容已经被移动了)...

谢谢!

【问题讨论】:

    标签: c# asp.net http redirect


    【解决方案1】:

    在进行重定向时使用Request.RawUrl 并将 domain1 替换为 domain2。

    来自备注部分:

    原始 URL 定义为 URL 中域之后的部分 信息。在 URL 字符串中 http://www.contoso.com/articles/recent.aspx,原始 URL 是 /articles/recent.aspx。原始 URL 包括查询字符串,如果 现在。

    更新:

    这个:

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

    绝对按您的需要工作。您可能会收到 404 错误,但这只是因为在 domain2 上不存在 Url 的路径部分(上例中的 google.com)。这是您应该能够预测/纠正或根本不用担心的事情。我不知道你的要求是什么。

    【讨论】:

    • @Garkbit:我会尝试 Application_BeginRequest。
    • 是的,我试过了,但是对于旧域中不存在的页面,我只会得到 404。
    【解决方案2】:

    您可以在 IIS 中进行重定向并跳过加载 ASP.NET 代码。

    在 IIS 的 domain1.com 的“HTTP 重定向”部分中,将重定向位置设置为:

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

    然后选中“将所有请求重定向到确切目的地(而不是相对目的地)”复选框。

    包括文件夹、文件和查询字符串参数在内的所有请求都将传递到新域。

    编辑

    由于您无权访问 IIS,因此您可以使用 Icarus 描述的 Request.RawUrl 方法。

    为避免404错误,可以在重定向前检查页面是否存在:

    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
    
    }
    

    【讨论】:

    • 听起来不错,只是我无法访问 IIS 管理器(Web 应用程序在我的托管服务提供商上运行)。
    猜你喜欢
    • 2015-11-23
    • 1970-01-01
    • 2018-04-13
    • 1970-01-01
    • 2014-11-02
    • 2015-10-24
    • 2016-03-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多