Matching Complex Query String Rewrite Rule in IIS

By March 22, 2017IIS

IIS URL Rewrite Doesn’t Find My Query String Rule. Help!

I recently had to handle a particular request from a client: They had sent out a newsletter that linked to their site, but had sent the wrong URL. As such, they needed the site to redirect the bad URL to the correct one. The bad URL linked to a page that passed along query string parameters. A simple request and a simple fix, right? Well, as I delved into the site’s rewrite rules, I quickly found out that the URL I needed to match was not matching. Worse still, it was making the site break! As it turns out, writing a query string rewrite rule takes a little more effort than simply doing an exact match on the URL itself.

First Attempt

Here’s the rule I started out with. I cracked open my separated rewrite rules config file and got to writing. Here’s what I ended up with at first (with details changed to protect the innocent):

If I didn’t have a complex query string (i.e. one with multiple parameters), or any query string at all for that matter, I’d be done. Instead my local development copy of the site went down! It was throwing an HTTP 500 error and nothing more. (Incidentally, this is why you never make changes, even simple ones, on production!) What gives?

Encoding the Ampersands and Splitting the Query String

In our query string rewrite rule, the first change is to encode the ampersands. Our web application in IIS was tripping up on those characters. We also need to move the query string. IIS reads the URL well enough in the <match> element, but the query string is a separate piece altogether, and needs to be moved to the <conditions> element instead.

We’re good now right? Wrong! While the site was no longer crashing down on me, the rewrite rule was not matching despite entering that exact URL. There was one smaller change I needed to make in order to get this query string rewrite rule matching.

Eliminating the Money and Making it Work

Our query string rewrite rule didn’t match because we specified the end-of-string regular expression symbol in our <match> element. IIS seems to ignore anything past that symbol, including items in the condition, despite my initial thinking. Once I got rid of the $ symbol, it all fell into place and began working. Here is the final, working query string rewrite rule:


In this case, a simple request led me on a little journey through the various workings of IIS rewrite. Despite working with it for some time now, I still managed to come across something new!

The following two tabs change content below.
  • Ashley Benson

    We glad to read your blog ……………..