In the following route configuration i want to make the height segment optional. So that

  • /images/400/200/placeholder.png
  • /images/400/placeholder.png

are both possible with one route.

$event->rules['/images/<width:\d+>/<height:\d+>/<imageName:([-\w.]+)>'] = 'module-name/image';

I tried the answer from this question Is it possible to define optional route segments? but couldnt bring it to work.

  • Note, the other question you linked to is showing an older Craft 2 syntax for routes. The example you provided in this question indicates you are using Craft 3/Yii2. Jul 3, 2018 at 16:26

1 Answer 1


Your regex is going to become more complex and potentially less specific if you try to address both scenarios in a single route as the height and width parameters match numbers and the final segment of your URL matches any characters that would be found in a URL segment.

It may be easier to handle this as two rules, the more specific one first:


Making this two rules you get around needing to matching both a number OR other characters in the third segment. If the second and third segment are numbers and the fourth segment is present, your first rule will match. If the third segment is not a number and there is no fourth segment, your second rule will match.

Also, with two rules you can easily test if height exists or not in your controller or template. If you combine that third segment into a compound rule, you may need additional logic in your template to sort out what value you are working with.

  • Somehow i "fogot" you can target the same controller with two routes... I think i tried to overcomplicate things. Thanks for the answer Ben!
    – Leonardo
    Jul 5, 2018 at 8:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.