2

I am trying to write a URL rewriter rule in IIS7. My current reg expression is ^(policy|pricing|contact|gallery)/(.*) My Rewrite rule is: /{R:1}.aspx?cat={R:2}

policy/ (Keep Slash in this case, WORKS)

gallery/soccer (No slash provided so this WORKS)

gallery/soccer/ (needs to remove last slash)

gallery/soccer/girls/ (needs to remove last slash)

Any ideas would be great, I know how I would approach this in languages like .Net, but I need to strictly do this as a regular expression rule in IIS.

jb.
  • 9,921
  • 12
  • 54
  • 90
NYTom
  • 524
  • 2
  • 14

3 Answers3

2

This might work

^(policy|pricing|contact|gallery)/([^/]*(?:/[^/]+)*)
1

I think the following should work:

^(policy|pricing|contact|gallery)/(.*?)/?$

The /? at the end means "match a / one or zero times", or in other words it is optional. Just adding this to the end wouldn't work because a / would still be consumed by the .*, so we need to change the .* to .*? so that it is no longer greedy.

The $ anchor is necessary so that the match doesn't end too early.

Note that the trailing / will still be a part of the match, but it will not be a part of the second capture group so your rewrite rule should work properly.

See it working: http://www.rubular.com/r/s8IqIlaqoz

Andrew Clark
  • 202,379
  • 35
  • 273
  • 306
  • @NYTom - No problem, you should [accept the answer](http://meta.stackexchange.com/a/5235/155356) that you think is best by clicking the outline of the check mark next to the answer. – Andrew Clark Apr 23 '12 at 17:47
0

I think that if you explicitly put it at the end (I have not escaped / because it looks like you're not doing so), you will effectively remove it in your re-write by not including that group.

^(policy|pricing|contact|gallery)/(.*)/?$

By adding $ we are ensuring that only a final forward slash is removed -- there can still be n forward slashes in between.

Jay
  • 56,361
  • 10
  • 99
  • 123
  • I tried that thanks, the problem is its still including the / at the end because ? is 0 or more times. If I use + (1 or more time) it will remove the slash if its there but if the input string doesn't have the slash at the end, then it wont find a match because the + says 1 or more, so its like a catch 22 problem. – NYTom Apr 23 '12 at 17:29