1
votes

For the last couple hours I tried to create a ReWrite Rule in IIS which does meet my requirements, but I just don't get it. So maybe someone can help me out :-)

What I have till now is the following:

Rewrite URL

index.php?page={R:1}&param={R:2}

RegEx Pattern

^(.*)/([0-9]+)

This is how I'd like to write my URLs at the end:

In this example I should have "news/detail" in "?page" and "1" in "?param".

With the rule I created so far that seems to work quite good, as long as I have a number at the end (param).

My only problem is that I want to make the number (param) optional.

Thanks a lot for your support.

2
What is the definitive rule? How many paths and/or parameters can be specified in the rule? - cheesemacfly
@cheesemacfly The definitive rule should be, that there should not be any limit in paths but its enough if one paramter can be set. Paths never have a number in it. - Crasher

2 Answers

0
votes

I can't come up with something more permissive than this:

^([a-z-/]+)([0-9])?

Base on your comment Paths never have a number in it, I went a bit further and allowed only characters from a to z (use the ignore case option if needed).
This rule will match any of the following url:

  • news/detail/1/ => {R:1} = news/detail/ and {R:2} = 1
  • news/detail/1 => {R:1} = news/detail/ and {R:2} = 1
  • news/detail/ => {R:1} = news/detail/ and {R:2} is empty
  • news/detail => {R:1} = news/detail and {R:2} is empty

You probably will have to deal with the trailing / in your code.

The limitation comes from the fact that as far as I know, the regex in the rewrite rule doesn't support negative lookahead/lookbehind pattern.

0
votes

To allow for the final match capture to be optional put a ? by it. Also specify that it will be at the by anchoring it with the end character $.

^(.*)/?(\d+)?$

I have also made the final / optional since if there is no digit you don't want match to fail if it does not have a / at the end (which should be optional).