Custom URL rules
Yii2 give us the opportunity to customize URL rules as we want. This can be done using the rules
property in urlManager
, an array where keys are patterns and values are corresponding routes. Patterns are common regular expression patterns, so it is necessary to have some familiarity with regular expression.
Patterns can contain parameters that will be passed to the route. In the next example, we will display a list of news that can be filtered through year or category parameter, based on parameters passed to the URL.
Example – list news items by year or category
In this example, we will create a new Controller named News
in controllers/NewsController.php
. In this new controller, we will insert a data()
function containing an array with test data, and a function named actionItemsList
.
The first thing to do is to configure the rules
property under the urlManager
component under config/web.php
:
'rules' => [ news/<year:\d{4}>/items-list' =>...