IIS URL Rewrite basic rewrite rules

URL Rewrite is built in IIS since IIS7, it helps to convert complex urls into easy to read urls, not only 
make it more readable for users but also search engine friendly. We will show you some basics about 
Rewrite rules.


Canonical Host Name
<rule name="Canonical Host Name" stopProcessing="true">
    <match url="(.*)" />
    <conditions>
        <add input="{HTTP_HOST}" pattern="^192.168.1.1$" negate="true" />
        <add input="{HTTP_HOST}" pattern="^example\.com$" />
        <add input="{HTTP_HOST}" pattern="^www\.example\.com$" negate="true" />
    </conditions>
    <action type="Redirect" url="http://www.example.com/{R:1}" />
</rule>
The rewrite rule above will redirect example.com to www.example.com  .

Match
<match url="(.*)" /> this means to match all urls

Conditions
<conditions> all urls must match the pattern inside the conditions tag.

<add input="{HTTP_HOST}" pattern="^192.168.1.1$" negate="true" />
this means that http host must match "192.168.1.1", with negate="true" means the url must not match
192.168.1.1.

<add input="{HTTP_HOST}" pattern="^example\.com$" />
this means that http host must match example.com  .

Action
Rewrite rule is performed when url match the rule pattern, in here we use Redirect action type, this way
rewrite moudle will send a redirect response to client, the browser will be redirected to www.example.com


 
<rule name="DifferentFolder" stopProcessing="true">
    <match url="^Examples/(.*).html$" />
    <action type="Rewrite" url="output/Examples/{R:1}.html" />
</rule>
this rule will convert
http://www.example.com/Examples/index.html
or
http://www.example.com/Examples/example-123.html
into output/Examples/index.html or output/Examples/example-123.html

 
<rule name="Rewrite With id" stopProcessing="true">
    <match url="^(Article)-(\d+).html$" />
    <action type="Rewrite" url="/Article/index.aspx?aid={R:2}" />
</rule>
this rule will convert
http://www.example.com/Article-123.html
into 
Article/index.aspx?aid=123






 
comments powered by Disqus