A few months ago Mads posted some IIS URL Rewrite rules in a post titled “URL rewrite and the www subdomain”.
Years ago, when I rewrote this site in ASP.NET MVC, I found URL rewriting to be invaluable. Some URLs in the new version of this site became obsolete. For example, an efficient Gravatar implementation from the Web Helpers library replaced an Identicon HTTP handler. I wanted to explicitly purge the handler from search engine results with an HTTP 410 response.
<rule name="obsolete identicon" stopProcessing="true"> <match url="/IdenticonHandler.ashx" /> <action type="CustomResponse" statusCode="410" statusReason="Gone" statusDescription="…" /> </rule>
Instead of having 4 different RSS feeds for different sections of the site, I collapsed all content into a single RSS feed. All previous RSS endpoints now redirect to FeedBurner.
<rule name="article rss feed" stopProcessing="true"> <match url="articles/rss.aspx" /> <action type="Redirect" url="http://feeds.feedburner.com/OdeToCode" redirectType="Permanent" /> </rule>
To make routing a bit easier, I wanted to avoid processing URLs like /articles or /blogs in ASP.NET and redirect those requests to to /articles/list with rules like the following.
<rule name="avoid articles directory" stopProcessing="true"> <match url="articles[/]?$" /> <action type="Redirect" url="articles/list" redirectType="Permanent" /> </rule>
A tricky scenario was preserving some endpoints that used the classic ASP.NET page name of “default.aspx” in the URL. For example, the list of all blog posts used to exist at /blogs/all/default.aspx, but I wanted to redirect these requests and avoid the page name.
<rule name="default page" stopProcessing="true"> <match url="(.*)default.aspx" /> <conditions> <add input="{REQUEST_URI}" negate="true" pattern="-default.aspx$" /> </conditions> <action type="Redirect" url="{r:1}" redirectType="Permanent" /> </rule>
The negation condition in the above rule avoids redirecting requests for blog posts with default.aspx in the title of the post, of which there are 1 or 2.
Finally, I use a web.config transformation to add an additional rule in production to enforce the canonical host name of odetocode.com.
<rule name="Canonical Host Name" stopProcessing="true" xdt:Transform="InsertBefore(/configuration/system.webServer/rewrite/rules/rule[1])"> <match url="(.*)" /> <conditions> <add input="{HTTP_HOST}" negate="true" pattern="^odetocode\.com$" /> </conditions> <action type="Redirect" url="https://odetocode.com/{R:1}" redirectType="Permanent" /> </rule>
One post I found useful when developing these rules was RuslanY’s “10 URL Rewriting Tips and Tricks”.