Friday, 15 June 2012

Url Rewriting in IIS7

The Microsoft URL Rewrite Module 2.0 for IIS 7 enables IIS administrators to create powerful customized rules to map request URLs to friendly URLs that are easier for users to remember and easier for search engines to find. You can use the URL Rewrite module to perform URL manipulation tasks.

Creating Rewrite Rules


To test how the URL Rewrite Module works, we will use ASP.NET page called "article.aspx". This page reads the Web server variables and outputs their values in the browser.

write a label in article.aspx page:


 <asp:Label ID="lblName" runat="server"></asp:Label>

and code also in "article.aspx.cs"


string strURL = "http://" + Settings.hostUrl;

string strValue = ; // user name value

this.lblName.Text  = "<a href='" + strURL + "/article/" + 
strValue + "'>" + strName.Replace(" ", "").Replace("_", "-") 
+ "</a>" + ", ";

We will create a rewrite rule by using URL Rewrite UI in IIS Manager. To do this follow these steps:

1. Go to IIS Manager.
2. Select Default Web Site.
3. In the feature --> click Url Rewrite

4. In the Actions on the right hand side --> click Add Rule

5. In the Add rule Dialogue --> select Blank Rule


Now you must define the actual rewrite rule. In the URL Rewrite Module, a rewrite rule is defined by four required types of information:
  • Name of the rule - Enter a name that will uniquely identify the rule, for ex. "Article Url".
  • Pattern to use for matching the URL string - Enter the following string  ^article/([0-9]+)/([_0-9a-z-]+) This string is a regular expression that specifies that the pattern will match any URL string that meets the following conditions:
    1. Starts with the sequence of characters 'article/".
    2. Contains one or more numeric characters after the first "/".
    3. Contains one or more alphanumeric or "_" or "-" characters after the second "/".
  • Optional set of conditions.
  • Action to perform if a pattern is matched and whether all conditions checks succeed - Choose the Rewrite action type that is listed in the Action group box. Enter the following string article.aspx?id={R:1}&title={R:2}
The Edit Rule property page should look like:



Save the rule by click apply.

Now, View the Rewrite Url in Web.Config file



<rewrite>

  <rules>

    <rule name="Article Url">

      <match url="^article/([0-9]+)/([_0-9a-z-]+)" />

      <action type="Rewrite" url="article.aspx?id={R:1}&amp;
title={R:2}" appendQueryString="false" logRewrittenUrl="true"/>

    </rule>

  </rules>

</rewrite> 

Testing the Url

 

http://localhost/article/123/title-name

You should see that the rewrite rule on your Web server has changed the original URL to Article.aspx and it has passed "123" and "title-name" as values for query string parameters.

Done.You have learned how to configure URL Rewrite Rules by using IIS Manager or by manually editing Web.config files. 

2 comments: