Solving URL rewriting problems with themes and trailing slashes
In a comment to an old post of mine about URL rewriting, a visitor named Tim has just asked how to solve a problem he was facing with ASP.NET themes and rewriting. The original post was addressing the main problems by using an overload of the RewritePath method introduced by .NET 2. Yet, a simple problem still existed: whenever URL rewriting is used with a URL like ~/somepath/ the theme gets broken because the path to the CSS files and other themed resources (like images) are wrong. The problem here is the trailing slash, which confuses the theme engine. A URL like ~/somepath works fine of course.
In fact, I recently noticed that I had the same problem with my own URLs on SharpToolbox/JavaToolbox and on a new site I'm working on. What I did to resolve this is to perform a (permanent) redirection to URLs without the ending "/". This is indeed what we wish to express: ~/somepath/ and ~/somepath are the same URLs.
Here is the regular expression I use to identify a problematic URL: ^(.*)/(\?.*)?$
I then redirect to: $1$2
You can notice that this expression also supports URLs with parameters.
If you use UrlRewritingNet.UrlRewrite you can use the following rule:
<add virtualUrl="^(.*)/(\?.*)?$" destinationUrl="$1$2" rewriteUrlParameter="ExcludeFromClientQueryString" redirectMode="Permanent" redirect="Domain" />
If you use my old HTTP module, you should be able to use:
<add targetUrl="^(.*)/(\?.*)?$" destinationUrl="$1$2" permanent="true" />