Henry
Henry

Reputation: 32915

How to dynamically add rules to IIS rewrite map?

The multitenant app I am working on require many rewrite rules to be inserted/deleted dynamically. With IIS, we are thinking of using rewrite map.

How do one insert rules to the rewrite map dynamically? manipulate the webconfig.xml directly? Would IIS pick up the changes immediately?

Is there a hard limit on how many rules can be added?

Or... is there a better way?

Thanks

Upvotes: 1

Views: 1914

Answers (1)

James Moberg
James Moberg

Reputation: 4475

Here are the generic rules I add to my local web.config file.

<rule name="301 Redirects for ColdFusion">
  <match url=".*" />
    <conditions>
      <add input="{ColdFusion301:{REQUEST_URI}}" pattern="(.+)" />
    </conditions>
  <action type="Redirect" url="{C:1}" appendQueryString="false" redirectType="Permanent" />
</rule>
<rule name="302 Redirects for ColdFusion">
  <match url=".*" />
    <conditions>
      <add input="{ColdFusion302:{REQUEST_URI}}" pattern="(.+)" />
    </conditions>
  <action type="Redirect" url="{C:1}" appendQueryString="false" redirectType="Temporary" />
</rule>

You then need to add temporary & permanent redirect rules to a separate rewritemaps.config file. My starter file looks like this with at least one (1) key/value rule.

<rewriteMaps>
    <rewriteMap name="ColdFusion301">
        <add key="/sample301" value="/" />
        <add key="/old_coffee.htm" value="/coffee.htm" />
        <add key="/Gifts/" value="/shop/" />
        <add key="/Gifts" value="/shop/" />
    </rewriteMap>
    <rewriteMap name="ColdFusion302">
        <add key="/sample302" value="/" />
    </rewriteMap>
</rewriteMaps>

You can generate this file using multiple methods. I wrote a CustomTag to parse the XML file, displaying the values in an editor and then rewrite the data directly back to the XML file.

In order for IIS to see the updated rules, you'll need to "touch" the dateLastModified of the web.config file. You can do this by using the setFileDate UDF setFileDate("#Rootdir#web.config", Now()).

http://www.cflib.org/udf/setFileDate

function setFileDate(filename){
    var newDate = Now();
    if (ArrayLen(Arguments) GTE 2) { newDate = arguments[2]; }
    if (not isdate(newDate)) { return false; }
    else if (newDate LT '1/1/1970') { return false; }
    if (not fileExists(filename)) { return false; }
    newDate = DateDiff("s", DateConvert("utc2Local", "January 1 1970 00:00"), newDate) * 1000;
    return CreateObject("java","java.io.File").init(JavaCast("string",filename)).setLastModified(newDate);
}

Upvotes: 2

Related Questions