将所有页面的 HTTP 重定向到 HTTPS

Redirect HTTP to HTTPS for all pages

如果我输入 example.com 它会重定向到 https://example.com as I want to. However when typing http://example.com/blog it still redirects to https://example.com

<rewrite>
      <rules>
        <clear/>
         <rule name="Force HTTPS" stopProcessing="true">
          <match url="(.*)" />
          <conditions>
            <add input="{HTTPS}" pattern="off" ignoreCase="true"/>
          </conditions>
          <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" appendQueryString="false" redirectType="Permanent" />
        </rule>
      </rules>
    </rewrite>

如何让它向用户写的任何内容添加 https?

您可以为控制器使用属性 [System.Web.Mvc.RequireHttps]。

如果你需要它在所有控制器上,你可以使用下面的代码(仅Asp.Net MVC6/core)。

public void ConfigureServices(IServiceCollection services)
{
  services.AddMvc(options =>
    {
        options.Filters.Add(typeof(RequireHttpsInProductionAttribute));
    });
}

注意:并且可以使用HSTS避免客户端下次使用http请求。

  <system.webServer>
    <httpProtocol>
      <customHeaders>
        <add name="Strict-Transport-Security" value="max-age=31536000"/>
      </customHeaders>
    </httpProtocol>
</system.webServer>