How to write a Redirect rule for an IIS web server inside a web.config file

The first important part is the "rule" element. Everything inside the opening and closing tags of this element describe what your rule does. The rule has a few attributes setup for the rule's name, pattern syntaxing, processing, and if it's enabled.

<rule name="Redirect to https" enabled="true" patternSyntax="Wildcard" stopProcessing="true"></rule>

The next child element is the start of our rule. Using the wildcard * inside the "match" element's url attribute tells the server to match any character found in your website's URL.

<match url="*" negate="false" />

Next we have the "conditions" element that lets the web server know to ignore any patterning matching for HTTPS requests.

 <conditions logicalGrouping="MatchAny">
    <add input="{HTTPS}" pattern="off" />
 </conditions>

Lastly we have the "action" element for the rule. This tells our server how to redirect the URL based on the match and conditions elements. This will redirect any URL found to https.

<action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" redirectType="Found" />

The entire XML file should look like the following:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <rewrite>
            <rules>
                <rule name="Redirect to http" enabled="true" patternSyntax="Wildcard" stopProcessing="true">
                    <match url="*" negate="false" />
                    <conditions logicalGrouping="MatchAny">
                        <add input="{HTTPS}" pattern="off" />
                    </conditions>
                    <action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" redirectType="Found" />
                </rule>
            </rules>
        </rewrite>
    </system.webServer>
</configuration>

Note: This XML file must be named web.config and be in the directory where you want the rules to be applied.


Comments

Popular posts from this blog

Build 6 is here

An example of chaining jQuery Ajax request callbacks

Creating hashtag hyperlinks on the fly for your website