C# 如何使用web.config文件强制HTTPS

C# 如何使用web.config文件强制HTTPS,c#,asp.net,iis,https,web-config,C#,Asp.net,Iis,Https,Web Config,我在谷歌和StackOverflow搜索过,试图找到解决方案,但它们似乎都与ASP.NET等相关 我通常在我的服务器上运行Linux,但对于这个客户端,我使用的是Windows和IIS 7.5(以及Plesk 10)。这就是为什么我对IIS和web.config文件有点不熟悉的原因。在.htaccess文件中,您可以使用重写条件来检测协议是否为HTTPS,并相应地重定向。使用web.config文件,甚至使用我安装的“URL Rewrite”模块,是否有一种简单的方法来实现这一点 我没有ASP.

我在谷歌和StackOverflow搜索过,试图找到解决方案,但它们似乎都与ASP.NET等相关

我通常在我的服务器上运行Linux,但对于这个客户端,我使用的是Windows和IIS 7.5(以及Plesk 10)。这就是为什么我对IIS和web.config文件有点不熟悉的原因。在
.htaccess
文件中,您可以使用重写条件来检测协议是否为HTTPS,并相应地重定向。使用web.config文件,甚至使用我安装的“URL Rewrite”模块,是否有一种简单的方法来实现这一点

我没有ASP.NET方面的经验,因此如果解决方案中涉及到这一点,请包括如何实施的明确步骤


我之所以使用web.config和而不是PHP这样做,是因为我想在网站内的所有资产上强制使用HTTPS。

您需要URL重写模块,最好是v2(我没有安装v1,所以不能保证它在那里工作,但应该可以)

下面是此类web.config的一个示例——它将强制所有资源使用HTTPS(使用301永久重定向):


p.S. 这个特定的解决方案与ASP.NET/PHP或任何其他技术无关,因为它只使用URL重写模块完成——在请求到达代码执行点之前,它在初始/较低级别进行处理。

一个简单的方法是告诉IIS为HTTP请求发送自定义错误文件。然后,该文件可以包含元重定向、JavaScript重定向和带有链接的指令等。。。重要的是,您仍然可以检查站点(或文件夹)的“需要SSL”,这将起作用


适用于使用ASP.NET MVC的用户。您可以使用requireHttpAttribute强制所有响应为HTTPS:

GlobalFilters.Filters.Add(new RequireHttpsAttribute());
您可能还需要做其他事情来保护您的站点:

  • 强制防伪令牌使用SSL/TLS:

    AntiForgeryConfig.RequireSsl = true;
    
  • 通过更改Web.config文件,要求Cookie在默认情况下要求HTTPS:

    <system.web>
        <httpCookies httpOnlyCookies="true" requireSSL="true" />
    </system.web>
    
  • 使用NWebSec.Owin NuGet包并添加以下代码行以在整个站点上启用公钥锁定(HPKP)。更多信息和信息

  • 在使用的任何URL中包括https方案。当您在某些浏览器中限制该方案时,HTTP头和不起作用。关于HTTPS最好是明确的。e、 g

    <script src="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.4/bootstrap.min.js">
    </script>
    
    
    
  • 使用VisualStudio项目模板生成包含所有这些以及更多内置内容的项目。您还可以在上查看代码

  • 卓越库可以使用
    Web.config
    中的
    upgrade unsecure requests
    标记将您的请求从HTTP升级到HTTPS:

    <nwebsec>
      <httpHeaderSecurityModule>
        <securityHttpHeaders>
          <content-Security-Policy enabled="true">
            <upgrade-insecure-requests enabled="true"  />
          </content-Security-Policy>
        </securityHttpHeaders>
      </httpHeaderSecurityModule>
    </nwebsec>
    

    为了补充LazyOne的答案,这里是答案的注释版本

    <rewrite>
      <rules>
         <clear />
         <rule name="Redirect all requests to https" stopProcessing="true">
           <match url="(.*)" />
             <conditions logicalGrouping="MatchAll">
               <add input="{HTTPS}" pattern="off" ignoreCase="true" />
             </conditions>
             <action 
                type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" 
                redirectType="Permanent" appendQueryString="false" />
         </rule>
      </rules>
    </rewrite>
    
    
    
    被接受的答案对我不起作用。 我遵循了这个步骤

    我缺少的一个关键点是,我需要下载并安装IIS的URL重写工具。我找到了。结果如下

    <rewrite>
            <rules>
                <remove name="Http to Https" />
                <rule name="Http to Https" enabled="true" patternSyntax="Wildcard" stopProcessing="true">
                    <match url="*" />
                    <conditions>
                        <add input="{HTTPS}" pattern="off" />
                    </conditions>
                    <serverVariables />
                    <action type="Redirect" url="https://{HTTPS_HOST}{REQUEST_URI}" />
                </rule>
            </rules>
        </rewrite>
    

    我不允许在我的环境中安装URL重写,因此,我找到了另一条路径

    将此添加到my web.config添加了错误重写,并在IIS 7.5上运行:

    <system.webServer>
        <httpErrors errorMode="Custom" defaultResponseMode="File" defaultPath="C:\WebSites\yoursite\" >    
        <remove statusCode="403" subStatusCode="4" />
        <error statusCode="403" subStatusCode="4" responseMode="File" path="redirectToHttps.html" />
    </httpErrors>
    
    
    
    然后,按照这里的建议:

    我将IIS网站配置为需要SSL,并在403()错误时创建了执行重定向的html文件(redirectToHttps.html):

    
    重定向。。。
    函数redirectHttpToHttps()
    {
    var httpURL=window.location.hostname+window.location.pathname+window.location.search;
    var httpsURL=“https://”+httpURL;
    window.location=httpsURL;
    }
    重定向httptohttps();
    

    我希望有人会觉得这很有用,因为我无法在其他地方找到所有的片段。

    在.Net Core中,按照

    在startup.cs中添加以下内容:

    // Requires using Microsoft.AspNetCore.Mvc;
    public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<MvcOptions>(options =>
        {
            options.Filters.Add(new RequireHttpsAttribute());
        });`enter code here`
    

    我正在使用下面的代码,它完美地为我工作,希望它将帮助你

    <configuration>
    <system.webServer>
        <rewrite>
            <rules>
                <rule name="Force redirect to https" stopProcessing="true">
                    <match url="(.*)" />
                    <conditions>
                        <add input="{HTTPS}" pattern="^OFF$" />
                    </conditions>
                    <action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" appendQueryString="false" />
                </rule>
            </rules>
        </rewrite>
    </system.webServer>
    
    
    
    @BenCarey您还应该查看
    严格传输安全性
    标题:我建议更改重定向,这样它就不会附加查询字符串,因为它已经是{REQUEST_URI}的一部分(否则会添加两次参数)<代码>
    这是可行的,但不幸的是,在本地主机上也是如此。为了避免这种情况,您可以将其添加到:使用AWS Elastic beanstalk,此方法给了我302个过多的重定向,直到我修改:
    @Sam可能您没有安装URL重写模块?默认情况下,它不随IIS提供,需要单独安装。例如,该问题要求使用ASP.NET,但没有说明WebForms或MVC,因此我为那些使用MVC(不使用Web.config文件强制使用HTTPS)的人提供了一个全面的答案,但是……被否决了。a)解决方案可行,但情况发生了变化,这个突出的、高评分的问题应该使用MVC内置的内容得到更新的答案。b) 答案试图涵盖所有基础。问题并不简单,在整个站点上启用HTTPS需要的远不止更改web.config文件。读者可能会被误导,以为只需更改Web.config文件即可。安全是很难的
    <html>
    <head><title>Redirecting...</title></head>
    <script language="JavaScript">
    function redirectHttpToHttps()
    {
        var httpURL= window.location.hostname + window.location.pathname + window.location.search;
        var httpsURL= "https://" + httpURL;
        window.location = httpsURL;
    }
    redirectHttpToHttps();
    </script>
    <body>
    </body>
    </html>
    
    // Requires using Microsoft.AspNetCore.Mvc;
    public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<MvcOptions>(options =>
        {
            options.Filters.Add(new RequireHttpsAttribute());
        });`enter code here`
    
    // Requires using Microsoft.AspNetCore.Rewrite;
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();
    
        var options = new RewriteOptions()
           .AddRedirectToHttps();
    
        app.UseRewriter(options);
    
    <configuration>
    <system.webServer>
        <rewrite>
            <rules>
                <rule name="Force redirect to https" stopProcessing="true">
                    <match url="(.*)" />
                    <conditions>
                        <add input="{HTTPS}" pattern="^OFF$" />
                    </conditions>
                    <action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" appendQueryString="false" />
                </rule>
            </rules>
        </rewrite>
    </system.webServer>