Rewrite rules for IIS web server inside a web.config file

I am going to show you the entire XML file upfront and then break down the important parts that make the magic happen. With that said, here is the XML file:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <rewrite>
            <rules>
                <rule name="profileurl1" enabled="true">
                    <match url="^([^/]+)/?$" />
                    <conditions>
                        <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
                        <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
                    </conditions>
                    <action type="Rewrite" url="index.php?page=profile&amp;user={R:1}" />
                </rule>
            </rules>
        </rewrite>
    </system.webServer>
</configuration>

The first important part is the "rule" element. Everything inside the opening and closing tags of this element describe what your rule does.

<rule name="profileurl1" enabled="true">
</rule>

The next child element is the start of our rule. The "match" element tells the server to match any character found in your website's URLs filename.

<match url="^([^/]+)/?$" />

Next we have the "conditions" element that lets the web server know what not to rewrite. That being if the requested filename is a file or a directory, do not rewrite the URL.

 <conditions>
    
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
    
 <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
</conditions>

Lastly we have the "action" element for the rule. This tells our server how to rewrite the URL based on the match and conditions elements. The {R:1} is replaced with any word found with our match element.

<action type="Rewrite" url="index.php?page=profile&amp;user={R:1}" />

In my next post I will show you how to do a simple redirect rule. 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