【问题标题】:How to redirect HTTP to HTTPS in MVC application (IIS7.5)如何在 MVC 应用程序(IIS7.5)中将 HTTP 重定向到 HTTPS
【发布时间】:2011-06-24 04:06:51
【问题描述】:

我需要将我的 HTTP 站点重定向到 HTTPS,添加了以下规则,但尝试使用 http://www.example.com 时出现 403 错误,当我在浏览器中键入 https://www.example.com 时它工作正常。

<system.webServer>
    <rewrite>
        <rules>
            <rule name="HTTP to HTTPS redirect" stopProcessing="true">
                <match url="(.*)" />
                <conditions>
                    <add input="{HTTPS}" pattern="off" ignoreCase="true" />
                </conditions>
                <action type="Redirect" redirectType="Found" url="https://{HTTP_HOST}/{R:1}" />
            </rule>
        </rules>
    </rewrite>
</system.webServer>

【问题讨论】:

  • 违反规则?什么意思?
  • 我在 IIS 下使用“URL rewirte”模块添加了规则,并且在 web.config 中。

标签: asp.net-mvc http redirect https


【解决方案1】:

你可以在代码中做到这一点:

Global.asax.cs

protected void Application_BeginRequest(){
    if (!Context.Request.IsSecureConnection)
        Response.Redirect(Context.Request.Url.ToString().Replace("http:", "https:"));
}

或者您可以将相同的代码添加到操作过滤器:

public class SSLFilter : ActionFilterAttribute {

    public override void OnActionExecuting(ActionExecutingContext filterContext){
        if (!filterContext.HttpContext.Request.IsSecureConnection){
            var url = filterContext.HttpContext.Request.Url.ToString().Replace("http:", "https:");
            filterContext.Result = new RedirectResult(url);
        }
    }
}

【讨论】:

  • 将我的重定向逻辑移动到 Application_BeginRequest() 解决了我在尝试根据输入的 URL 进行重定向时遇到的问题。
  • Application_BeginRequest() 非常适合我,谢谢。
  • 代码不是很正确:下面的urlhttp://example.com?someParam=http:会被转换成https://example.com?someParam=https:修改参数字符串,考虑使用string url = "https://" + filterContext.HttpContext.Request.Url.Host + filterContext.HttpContext.Request.RawUrl;(取自RequireHttpsAttribute也做同样的事情)
  • @cloudguy 我建议将其发布为答案
  • 如果 url 的参数中包含一个 url 或其他一些http:,它也会被转换。所以我认为你应该在第 4 位添加 s:Response.Redirect(Context.Request.Url.ToString().Insert(4, "s"));。看我的回答
【解决方案2】:

Global.asax.cs

简单重定向

protected void Application_BeginRequest()
{
    if (!Context.Request.IsSecureConnection
        && !Context.Request.IsLocal // to avoid switching to https when local testing
        )
    {
        // Only insert an "s" to the "http:", and avoid replacing wrongly http: in the url parameters
        Response.Redirect(Context.Request.Url.ToString().Insert(4, "s"));
    }
}

301 重定向:SEO 最佳实践(搜索引擎优化)

301 Moved Permanently 重定向状态响应代码被认为是将用户从 HTTP 升级到 HTTPS (see Google recommendations) 的最佳实践。

因此,如果 Google 或 Bing 机器人也将被重定向,请考虑以下问题:

protected void Application_BeginRequest()
{
    if (!Context.Request.IsSecureConnection
        && !Context.Request.IsLocal // to avoid switching to https when local testing
        )
    {
        Response.Clear();
        Response.Status = "301 Moved Permanently";
        Response.AddHeader("Location", Context.Request.Url.ToString().Insert(4, "s"));
        Response.End();
    }
}

【讨论】:

  • 应该选择回答 IMO,而不是我希望 OP 在 5 年后回来。
  • @Matthieu Charbonnier 非常感谢
  • 我同意上面的帖子-应该选择这个答案
  • @Matthieu:为什么不使用!Context.Request.IsLocal
  • @stomy 因为我不知道IsLocal 属性。谢谢:)
【解决方案3】:

我在 Global.asax 中使用以下内容:

protected void Application_BeginRequest()
{
  if (FormsAuthentication.RequireSSL && !Request.IsSecureConnection)
  {
    Response.Redirect(Request.Url.AbsoluteUri.Replace("http://", "https://"));
  }
}

【讨论】:

  • 不完整,因为url参数中的http也会被替换。 See my answer
【解决方案4】:

我在 Web.config 文件中有以下 ASP.NET MVC 重写规则:

您可以使用 web.config 文件尝试此代码。如果您的网址是http://www.example.com,那么它将被重定向到此网址https://www.example.com

<system.webServer>
    <rewrite>
        <rules>
             <rule name="http to https" stopProcessing="true">
              <match url="(.*)" />
              <conditions>
               <add input="{HTTPS}" pattern="^OFF$" />
              </conditions>
              <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" redirectType="Permanent" />
            </rule>
        </rules>
    </rewrite>
</system.webServer>

【讨论】:

  • 干得好,先生。最简单的方法!
【解决方案5】:

对于简单的情况,您可以使用 RequireHttpsAttribute。

[RequireHttps]
public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }
}

如 MSDN 中所述...

"表示一个属性,它强制一个不安全的 HTTP 请求被 通过 HTTPS 重新发送。”

RequireHttpsAttribute

不过,我不确定您是否希望使用它在大型网站上强制实施 HTTPS。有很多装饰要做,还有机会错过控制器。

【讨论】:

  • 如果你有子动作(渲染动作)则不起作用;-)
  • 好地方,在这种情况下它有什么作用?
  • 只是崩溃。 “不允许子动作执行重定向动作。” “异常详细信息:System.InvalidOperationException:不允许子动作执行重定向动作。”
【解决方案6】:

这很简单。只需在“Global.asax”文件中添加一行如下:

protected void Application_Start()
{
    GlobalFilters.Filters.Add(new RequireHttpsAttribute(true));
}

如果您只想应用服务器端,而不是本地端,请应用以下代码:

protected void Application_Start()
{
   if (!HttpContext.Current.Request.IsLocal)
         GlobalFilters.Filters.Add(new RequireHttpsAttribute(true));
}

希望对你有帮助:) 谢谢!

【讨论】:

    【解决方案7】:

    在 web.config 文件中使用此代码将 http:// 重定向到 https://

    <configuration>
      <system.webServer>
        <rewrite>
            <rules>
                <rule name="HTTPS force" enabled="true" stopProcessing="true">
                    <match url="(.*)" />
                    <conditions>
                        <add input="{HTTPS}" pattern="^OFF$" />
                    </conditions>
                    <action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" redirectType="Permanent" />
                </rule>
            </rules>
        </rewrite>
       </system.webServer></configuration>
    

    【讨论】:

      【解决方案8】:

      我是这样做的,因为本地调试会话使用自定义端口号:

          protected void Application_BeginRequest()
          {
              if (!Context.Request.IsSecureConnection)
              {
                  if (HttpContext.Current.Request.IsLocal)
                  {
                      Response.Redirect(Context.Request.Url.ToString().Replace("http://localhost:25885/", "https://localhost:44300/"));
                  }
                  else
                  {
                      Response.Redirect(Context.Request.Url.ToString().Replace("http://", "https://"));
                  }
              }
          }
      

      最好有某种方式以编程方式获取 URL 和 SSL URL...

      【讨论】:

        【解决方案9】:

        仅当网站在服务器上午餐时强制使用 https,并在您的机器上运行网站进行开发时忽略它:

        在 Global.asax 中:

        您需要 Application_BeginRequest() 方法

        public class MvcApplication : System.Web.HttpApplication
        {
            protected void Application_Start()
            {
                 // .....
            }
        
            //force https on server, ignore it on local machine
            protected void Application_BeginRequest()
            {
                if (!Context.Request.IsSecureConnection && !Context.Request.Url.ToString().Contains("localhost"))
                    Response.Redirect(Context.Request.Url.ToString().Replace("http:", "https:"));
            }
        }
        

        【讨论】:

          【解决方案10】:

          这个答案并不完全适用于 OP,而是适用于那些无法像我一样工作并且遇到过这个问题的人(虽然我知道 OP 中存在 403 而不是 404 错误),如果你得到,请参考这个答案404 代替:https://stackoverflow.com/a/6962829/5416602

          请检查您的 IIS 中是否绑定了 HTTP 端口 (80) 而不仅仅是 HTTPS 端口 (443)

          【讨论】:

            【解决方案11】:

            我无法添加 cmets,但认为此补充信息可能会对某人有所帮助。

            我使用 301 永久重定向实现了 Global.asax 的想法,并在 IIS 中将 http 绑定添加到站点。它仍然给了我 403 Forbidden,直到我记得在 SSL 设置中取消勾选“需要 SSL”。

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 2017-05-16
              • 2014-02-05
              • 2023-03-28
              • 2014-12-20
              • 2018-02-06
              • 1970-01-01
              • 2014-07-17
              相关资源
              最近更新 更多