Reputation: 151
I've recently implemented IIS URL Rewriting on one of my websites. I'm using URL Redirection rather than rewriting for everything. All of my static redirections are working perfectly, however, there's one specific type of dynamic redirection that I can't seem to make work.
I had old URL's that looked like this:
http://example.com/?tag=mytag
I'd like this to be redirected to the new URL format of:
http://example.com/tag/mytag
For these URL's the querystring key (tag) is known and fixed, however, the querystring value ("mytag" in the example above) is entirely dynamic and unknown in advance (so I don't believe it's therefore possible to use IIS Rewrite Maps).
Is is possible to add an IIS Rewrite rule that performs this kind of redirection for all possible querystring values that may be supplied?
Upvotes: 1
Views: 1936
Reputation: 3644
Yes, the guts of the solution are below. Whats going on is...
1st condition means only apply this rule to the top level of the site. So http://example.com/?tag=mytag
will redirect, whereas http://example.com/foobar/?tag=mytag
wouldnt.
2nd condition is the magic. It only runs if a query param called tag
exists, and the (.*)
is a regex to grab the value for use in the new URL.
The action uses the value you grabbed in the 2nd condition referenced as {C:1}
. appendQueryString does exactly what it says - set as appropriate. redirectType should be left as Temporary
(HTTP response code 307) until your happy, then change it to Permanent
(HTTP response code 301). Once you send a 301 response the client(/search engine) will potentially cache the response and not re-request from the server causing problems if you make a mistake.
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<rewrite>
<rules>
<rule name="Redirect based on tag query value">
<conditions>
<add input="{REQUEST_URI}" pattern="$" />
<add input="{QUERY_STRING}" pattern="tag=(.*)" />
</conditions>
<action type="Redirect" url="tag/{C:1}/" appendQueryString="false" redirectType="Temporary" />
</rule>
</rules>
</rewrite>
</system.webServer>
</configuration>
Upvotes: 3