Is it possible to have optional route segments/variables with getCpRoutes() and getSiteRoutes()?

I'd like the following route to work, even if the URI only contains one segment ("myplugin") rather than two ("myplugin/somevalue"):

"myplugin/(?P<myVariable>[-\w]+)" => array( "action" => "myPlugin/myAction" )

How would the regexp look? Is it even possible, or do I need another route pointing to the same action, but omitting the myVariable segment?

This question is kind of a follow up to Route that should be matching numbers not matching a zero?

  • 1
    Did you try to simply make that capturing group optional myplugin/(?P<myVariable>[-\w]+)? or myplugin(/(?P<myVariable>[-\w]+))??
    – carlcs
    Mar 8, 2015 at 10:22
  • I did not, and the latter suggestion (myplugin(/(?P<myVariable>[-\w]+))?) works! Thanks a lot – feel free to add your comment as an answer. Mar 8, 2015 at 10:27

1 Answer 1


You can make a capturing group optional, simply append ? to it. In this case you'd need to add an additional group that includes the backslash and make it optional.

"myplugin(/(?P<myVariable>[-\w]+))?" => array("action" => "myPlugin/myAction")

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.