簡體   English   中英

如何在 MVC 應用程序(IIS7.5)中將 HTTP 重定向到 HTTPS

[英]How to redirect HTTP to HTTPS in MVC application (IIS7.5)

我需要將我的 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>

你可以在代碼中做到這一點:

全局.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);
        }
    }
}

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 的最佳實踐(請參閱 Google 推薦)。

因此,如果 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();
    }
}

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

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

我在 Web.config 文件中有以下 ASP.NET MVC 重寫規則:

您可以使用 web.config 文件嘗試此代碼。 如果您的 URL 是http://www.example.com那么它將被重定向到這個 URL 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>

對於簡單的情況,您可以使用 RequireHttpsAttribute。

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

如 MSDN 中所述...

“表示強制通過 HTTPS 重新發送不安全的 HTTP 請求的屬性。”

RequireHttps屬性

不過,我不確定您是否願意使用它在大型網站上強制執行 HTTPS。 有很多裝飾要做,還有機會錯過控制器。

在 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>

這很簡單。 只需在“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));
}

希望對您有所幫助:)謝謝!

我是這樣做的,因為本地調試會話使用自定義端口號:

    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 ...

僅當網站在服務器上啟動時強制使用 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:"));
    }
}

這個答案並不完全適用於 OP,但對於那些不能像我一樣工作並且遇到過這個問題的人(雖然我知道 OP 中有 403 而不是 404 錯誤),如果你得到 404,請參考這個答案: https://stackoverflow.com/a/6962829/5416602

請檢查您的 IIS 中是否綁定了 HTTP 端口 (80) 而不僅僅是 HTTPS 端口 (443)

我無法添加評論,但認為此補充信息可能會對某些人有所幫助。

我用 301 永久重定向實現了 Global.asax 的想法,並在 IIS 中向網站添加了 http 綁定。 它仍然給了我 403 Forbidden,直到我記得在 SSL 設置中取消勾選“需要 SSL”。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM