web.config Redirect http to https

Windows server with IIS allows website redirects to be configured in the web.config file, located at the root of the website files directory.

I wished to add the following rule to redirect http web pages to https

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

The web.config file provides the main configuration and settings for asp.net server application framework and the website server.

The file is organised as a series of settings within a nested structure. Each item is wrapped within a less than and greater than pair.  Shown below is an example web.config file:

<?xml version="1.0"?>
<configuration>
   <system.web>
     .. existing text ..
     .. existing text ..
   </system.web>
   <system.webServer>
      <defaultDocument enabled="true">
         <files>      
            <clear/>              
            <add value="index.html"/>
            <add value="default.aspx/>
         </files>
      </defaultDocument>
   </system.webServer>
</configuration>

The rule is added to the rewrite section within the system.webserver section.

Open the web.config file with an HTML editor. I use Geany or Bluefish if using an Apple Mac.

Scroll down the file looking for the web.server section. It begins <system.webserver>.

If there are already redirect rules configured there’ll be a section for these. The wrappers for the rules begins:

<rewrite>
  <rules>

Its possible that rules have not previously been configured and will need to be added.

Shown below is the same basic web.config file with the redirect rules for http to https added:

<?xml version="1.0"?>
<configuration>
   <system.web>
     .. existing text ..
     .. existing text ..
   </system.web>
   <system.webServer>
      <defaultDocument enabled="true">
         <files>      
            <clear/>              
            <add value="index.html"/>
            <add value="default.aspx/>
         </files>
      </defaultDocument>
      <rewrite>
        <rules>
          <rule name="Redirect to HTTPS" stopProcessing="true">
            <match url="(.*)" />
              <conditions>
                <add input="{HTTPS}" pattern="^OFF$" />
              </conditions>
            <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" redirectType="SeeOther" />
          </rule>
        </rules>
      </rewrite>
   </system.webServer>
</configuration>

Wikipedia has a rather short entry for the web.config file.