Removing .aspx from pages using rewriteModule?

These are the standard rewrite rules I start every project with. I use only clean URLs for all the pages (example first rule works for www.example.com/about and second rule www.example.com/product/123)

<rewrite>
<rules>
  <rule name="Rewrite default to aspx" stopProcessing="true">
    <match url="^$" ignoreCase="false" />
    <action type="Rewrite" url="default.aspx" />
  </rule>
  <rule name="Rewrite page to aspx" stopProcessing="true">
    <match url="^([a-z0-9/]+)$" ignoreCase="false" />
    <action type="Rewrite" url="{R:1}.aspx" />
  </rule> 
</rules>
</rewrite>

Pages where I need to parse out the ID (this case number only) and add it to the query string I add a similar rule to the front:

<rule name="Rewrite Product ID" stopProcessing="true">
  <match url="^product/([0-9]+)$" ignoreCase="false"/>
  <action type="Rewrite" url="product.aspx?id={R:1}"/>
</rule>

If you want to use lower and upper case letters in the URL, set ignoreCase=”true”

Edit to answer your second question plus a bonus

This rule will redirect aspx page to the clean URL:

<rule name="Redirect to clean URL" stopProcessing="true">
  <match url="^([a-z0-9/]+).aspx$" ignoreCase="true"/>
  <action type="Redirect" url="{R:1}"/>
</rule>

Replace url=”{R:1}” with url=”{ToLower:{R:1}}” to change URL to lowercase. See below why you would want to do this.

Also a good idea to update the Form action so that post backs don’t return back to the ugly URL. Using IIS 7.5 or newer this should work:

 if (!String.IsNullOrEmpty(Request.RawUrl))
        form1.Action = Request.RawUrl;

or for IIS 7:

 if (!String.IsNullOrEmpty(Context.Request.ServerVariables["HTTP_X_ORIGINAL_URL"]))
        form1.Action = Context.Request.ServerVariables["HTTP_X_ORIGINAL_URL"];

One more thing to keep in mind… it’s a good idea to keep all URLs lower case. Mixing lower/upper case characters in the URL creates duplicate content issues for SEO/Google. For example website.com/About and website.com/about will load the same page, but Google will index them as two separate pages.

Leave a Comment