258

I have searched around Google and StackOverflow trying to find a solution to this, but they all seem to relate to ASP.NET etc.

I usually run Linux on my servers but for this one client I am using Windows with IIS 7.5 (and Plesk 10). This being the reason why I am slightly unfamiliar with IIS and web.config files. In an .htaccess file you can use rewrite conditions to detect whether the protocol is HTTPS and redirect accordingly. Is there a simple way to achieve this using a web.config file, or even using the 'URL Rewrite' module that I have installed?

I have no experience with ASP.NET so if this is involved in the solution then please include clear steps of how to implement.

The reason for me doing this with the web.config and not PHP is that I would like to force HTTPS on all assets within the site.

3

10 Answers 10

506

You need URL Rewrite module, preferably v2 (I have no v1 installed, so cannot guarantee that it will work there, but it should).

Here is an example of such web.config -- it will force HTTPS for ALL resources (using 301 Permanent Redirect):

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <rewrite>
            <rules>
                <clear />
                <rule name="Redirect to https" stopProcessing="true">
                    <match url=".*" />
                    <conditions>
                        <add input="{HTTPS}" pattern="off" ignoreCase="true" />
                    </conditions>
                    <action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" redirectType="Permanent" appendQueryString="false" />
                </rule>
            </rules>
        </rewrite>
    </system.webServer>
</configuration>

P.S. This particular solution has nothing to do with ASP.NET/PHP or any other technology as it's done using URL rewriting module only -- it is processed at one of the initial/lower levels -- before request gets to the point where your code gets executed.

22
  • 6
    @BenCarey You should also look at Strict-Transport-Security header: en.wikipedia.org/wiki/HTTP_Strict_Transport_Security
    – LazyOne
    Commented Mar 22, 2012 at 13:37
  • 29
    I recommend changing the redirect so that it doesn't append the query string as it is already part of {REQUEST_URI} (otherwise the parameters get added twice). <action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" redirectType="Permanent" appendQueryString="false" />
    – franzo
    Commented Jan 18, 2014 at 5:14
  • 10
    This works, but unfortunately also on localhost. To avoid this you can add this to <conditions>: <add input="{HTTP_HOST}" pattern="localhost" negate="true" />
    – wezzix
    Commented Aug 17, 2017 at 15:29
  • 6
    Using AWS Elastic beanstalk, this method was giving me a 302 Too many redirects until I modified: <match url=".*"/> to <match url="http://*.*" />
    – Kevin R.
    Commented Dec 12, 2017 at 21:05
  • 1
    @Sam Maybe you do not have URL Rewrite module installed? It does not come with IIS by default, needs to be installed separately. E.g. learn.microsoft.com/en-us/iis/extensions/url-rewrite-module/…
    – LazyOne
    Commented Jul 26, 2019 at 7:57
85

For those using ASP.NET MVC. You can use the RequireHttpsAttribute to force all responses to be HTTPS:

GlobalFilters.Filters.Add(new RequireHttpsAttribute());

Other things you may also want to do to help secure your site:

  1. Force Anti-Forgery tokens to use SSL/TLS:

    AntiForgeryConfig.RequireSsl = true;
    
  2. Require Cookies to require HTTPS by default by changing the Web.config file:

    <system.web>
        <httpCookies httpOnlyCookies="true" requireSSL="true" />
    </system.web>
    
  3. Use the NWebSec.Owin NuGet package and add the following line of code to enable Strict Transport Security (HSTS) across the site. Don't forget to add the Preload directive below and submit your site to the HSTS Preload site. More information here and here. Note that if you are not using OWIN, there is a Web.config method you can read up on on the NWebSec site.

    // app is your OWIN IAppBuilder app in Startup.cs
    app.UseHsts(options => options.MaxAge(days: 720).Preload());
    
  4. Use the NWebSec.Owin NuGet package and add the following line of code to enable Public Key Pinning (HPKP) across the site. More information here and here.

    // app is your OWIN IAppBuilder app in Startup.cs
    app.UseHpkp(options => options
        .Sha256Pins(
            "Base64 encoded SHA-256 hash of your first certificate e.g. cUPcTAZWKaASuYWhhneDttWpY3oBAkE3h2+soZS7sWs=",
            "Base64 encoded SHA-256 hash of your second backup certificate e.g. M8HztCzM3elUxkcjR2S5P4hhyBNf6lHkmjAHKhpGPWE=")
        .MaxAge(days: 30));
    
  5. Include the https scheme in any URL's used. Content Security Policy (CSP) HTTP header and Subresource Integrity (SRI) do not play nice when you imit the scheme in some browsers. It is better to be explicit about HTTPS. e.g.

    <script src="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.4/bootstrap.min.js">
    </script>
    
  6. Use the ASP.NET MVC Boilerplate Visual Studio project template to generate a project with all of this and much more built in. You can also view the code on GitHub.

18
  • 4
    The question asks for ASP.NET but does not state WebForms or MVC, so I gave a comprehensive answer for those using MVC (Which does not use the Web.config file to force HTTPS) and yet...downvoted. Commented Mar 20, 2015 at 10:31
  • 7
    a) The solution works but things have changed, this prominent, high rated question deserves an updated answer using what's built into MVC. b) The answer tries to cover all bases. The question is not simple, enabling HTTPS over an entire site requires a lot more than changing a web.config file. Readers may be misled into thinking changing a Web.config file is all it takes. Security is hard enough as it is without incomplete/outdated answers. Commented Mar 20, 2015 at 14:14
  • 12
    In my opinion this is an excellent and valuable answer. When someone googles the topic and is directed to this question I'm glad your answer is here. Commented Mar 21, 2015 at 11:26
  • 1
    @MuhammadRehanSaeed Nice post. Maybe add SRI to your list? scotthelme.co.uk/subresource-integrity
    – Nathan
    Commented Jan 26, 2016 at 12:21
  • 1
    @MuhammadRehanSaeed true - I guess your heading of "Other things you may also want to do to help secure your site" made me think of it :)
    – Nathan
    Commented Jan 26, 2016 at 13:48
25

To augment LazyOne's answer, here is an annotated version of the answer.

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

Clear all the other rules that might already been defined on this server. Create a new rule, that we will name "Redirect all requests to https". After processing this rule, do not process any more rules! Match all incoming URLs. Then check whether all of these other conditions are true: HTTPS is turned OFF. Well, that's only one condition (but make sure it's true). If it is, send a 301 Permanent redirect back to the client at http://www.foobar.com/whatever?else=the#url-contains. Don't add the query string at the end of that, because it would duplicate the query string!

This is what the properties, attributes, and some of the values mean.

  • clear removes all server rules that we might otherwise inherit.
  • rule defines a rule.
    • name an arbitrary (though unique) name for the rule.
    • stopProcessing whether to forward the request immediately to the IIS request pipeline or first to process additional rules.
  • match when to run this rule.
    • url a pattern against which to evaluate the URL
  • conditions additional conditions about when to run this rule; conditions are processed only if there is first a match.
    • logicalGrouping whether all the conditions must be true (MatchAll) or any of the conditions must be true (MatchAny); similar to AND vs OR.
  • add adds a condition that must be met.
    • input the input that a condition is evaluating; input can be server variables.
    • pattern the standard against which to evaluate the input.
    • ignoreCase whether capitalization matters or not.
  • action what to do if the match and its conditions are all true.
    • type can generally be redirect (client-side) or rewrite (server-side).
    • url what to produce as a result of this rule; in this case, concatenate https:// with two server variables.
    • redirectType what HTTP redirect to use; this one is a 301 Permanent.
    • appendQueryString whether to add the query string at the end of the resultant url or not; in this case, we are setting it to false, because the {REQUEST_URI} already includes it.

The server variables are

  • {HTTPS} which is either OFF or ON.
  • {HTTP_HOST} is www.mysite.com, and
  • {REQUEST_URI} includes the rest of the URI, e.g. /home?key=value
  • the browser handles the #fragment (see comment from LazyOne).

See also: https://www.iis.net/learn/extensions/url-rewrite-module/url-rewrite-module-configuration-reference

6
  • 1
    One note though: fragment part of URL (from /home?key=value#fragment) is not set to the server by browsers as it meant to be used locally.
    – LazyOne
    Commented Jan 18, 2017 at 11:26
  • @LazyOne Question. We're using the above web.config successfully to redirect from greenearth.game/about#foo to HTTPS. The switch to HTTPS includes the #foo fragment. Given that the #foo part is not sent to the sever, how does the redirect include it? Commented Jan 18, 2017 at 16:39
  • It's handled by browser. Just open network tab in Google Chrome (or similar in Firefox etc) and see what URL is actually requested (e.g. for http://www.example.com/members#oops request will be sent to http://www.example.com/members which then gets redirected to HTTPS version at https://www.example.com/members -- browser does the rest)
    – LazyOne
    Commented Jan 18, 2017 at 16:56
  • @LazyOne Thank you for that. If I recall correctly, there are a few WebKit bugs that prevent the fragment from being included in redirects. So, this makes sense. bugs.webkit.org/show_bug.cgi?id=24175 Commented Jan 18, 2017 at 17:00
  • 1
    en.wikipedia.org/wiki/Fragment_identifier -- "Clients are not supposed to send URI-fragments to servers when they retrieve a document, and without help from a local application (see below) fragments do not participate in HTTP redirections" -- just to be clear in case I misunderstood your last comment.
    – LazyOne
    Commented Jan 18, 2017 at 17:13
10

The accepted answer did not work for me. I followed the steps on this blog.

A key point that was missing for me was that I needed to download and install the URL Rewrite Tool for IIS. I found it here. The result was the following.

<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>
1
  • Adding the rewrite tool worked for me. Thanks!
    – Shawn
    Commented Jan 8, 2022 at 19:36
1

In .Net Core, follow the instructions at https://learn.microsoft.com/en-us/aspnet/core/security/enforcing-ssl

In your startup.cs add the following:

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

To redirect Http to Https, add the following in the startup.cs

// 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);
0

The excellent NWebsec library can upgrade your requests from HTTP to HTTPS using its upgrade-insecure-requests tag within the Web.config:

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

I am using below code and it perfect works for me, hope it will help you.

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

I was not allowed to install URL Rewrite in my environment, so, I found another path.

Adding this to my web.config added the error rewrite and worked on 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>

Then, following the advice here: https://www.sslshopper.com/iis7-redirect-http-to-https.html

I configured the IIS website to require SSL and created the html file that does the redirect (redirectToHttps.html) upon the 403 (Forbidden) error:

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

I hope someone finds this useful as I could not find all of the pieces in one place anywhere else.

0
0

You have to configure redirection as below, when you are using IIS 10 with application load balancer on AWS.

        <rule name="Force HTTPS" enabled="true" stopProcessing="true">
            <match url="(.*)" />
            <conditions logicalGrouping="MatchAll" trackAllCaptures="false">
                <add input="{HTTP_X_Forwarded_Proto}" pattern="^https$" negate="true" />
                <add input="{HTTP_HOST}" pattern="^(www\.)?dname\.com$" />
            </conditions>
            <action type="Redirect" url="https://www.dname.com{REQUEST_URI}" />
        </rule>

If you have sub domain redirection use below:

        <!--START REDIRECT TO HTTPS-->
        <rule name="Force HTTPS" enabled="true" stopProcessing="true">
            <match url="(.*)" />
            <conditions logicalGrouping="MatchAll" trackAllCaptures="false">
                <add input="{HTTP_X_Forwarded_Proto}" pattern="^https$" negate="true" />
                <add input="{HTTP_HOST}" pattern="subdomain\.domain\.com$" />
            </conditions>
            <action type="Redirect" url="https://subdomain.domain.com{REQUEST_URI}" />
        </rule> 
        <!--END REDIRECT TO HTTPS-->    
-8

A simple way is to tell IIS to send your custom error file for HTTP requests. The file can then contain a meta redirect, a JavaScript redirect and instructions with link, etc... Importantly, you can still check "Require SSL" for the site (or folder) and this will work.

</configuration>
</system.webServer>
    <httpErrors>
        <clear/>
        <!--redirect if connected without SSL-->
        <error statusCode="403" subStatusCode="4" path="errors\403.4_requiressl.html" responseMode="File"/>
    </httpErrors>
</system.webServer>
</configuration>
2
  • Why is the downvote? It works and answers the question.
    – redirect
    Commented Mar 23, 2015 at 18:41
  • 16
    This is a down vote because you're telling Google that your file isn't found and then you're using JavaScript to redirect, which is typically just bad. Commented Sep 16, 2015 at 15:02

Not the answer you're looking for? Browse other questions tagged or ask your own question.