yuppo
yuppo

Reputation: 23

Using RegEx within Yii 2's UrlManager rules, doesn't work

Yii2 urlManager, I want to write a regex that looks like below.

*.*com/bj/haidian/ is good.

*.*com/bj/haidian does not work.

'urlManager' => [
        'enablePrettyUrl' => true,
        'showScriptName' => false,
        'rules' => [
            '<module:\w+>/<controller:\w+>/<action:\w+>' => '<module>/<controller>/<action>',
            "<controller:\w+>/<action:\w+>/<id:\d+>" => "<controller>/<action>",
            "<controller:\w+>/<action:\w+>" => "<controller>/<action>",
            '<module:\w+>/<action:\w+>/<id:\d+>' => '<module>/default/<action>',
            '<module:\w+>/<controller:\w+>' => '<module>/<controller>/index',
            'bj|sh|gz|sz|cd|xa|wh|hz|tj|dl/?'=>'/sem/weight',
            'bj|sh|gz|sz|cd|xa|wh|hz|tj|dl/<district:[0-9a-zA-Z\_\-]+>/?' => '/sem/weight',
            'bj|sh|gz|sz|cd|xa|wh|hz|tj|dl/<district:[0-9a-zA-Z\_]+>/<cond:[0-9a-zA-Z\_]+>/?' => '/sem/weight',
        ],
    ],

Upvotes: -1

Views: 1350

Answers (1)

Muhammad Omer Aslam
Muhammad Omer Aslam

Reputation: 23778

Your rules should be before the default rules or parameterized routes not after them otherwise your rules work fine on my side I just tested all 3 of them, just change the sequence to the following.

'urlManager' => [
        'class' => 'yii\web\UrlManager',
        'enablePrettyUrl' => true,
        'showScriptName' => false,
        'rules' => [
            'bj|sh|gz|sz|cd|xa|wh|hz|tj|dl/?'=>'/sem/weight',
            'bj|sh|gz|sz|cd|xa|wh|hz|tj|dl/<district:[0-9a-zA-Z\_\-]+>/?' => '/sem/weight',
            'bj|sh|gz|sz|cd|xa|wh|hz|tj|dl/<district:[0-9a-zA-Z\_]+>/<cond:[0-9a-zA-Z\_]+>/?' => '/sem/weight',
            '<module:\w+>/<controller:\w+>/<action:\w+>' => '<module>/<controller>/<action>',
            "<controller:\w+>/<action:\w+>/<id:\d+>" => "<controller>/<action>",
            "<controller:\w+>/<action:\w+>" => "<controller>/<action>",
            '<module:\w+>/<action:\w+>/<id:\d+>' => '<module>/default/<action>',
            '<module:\w+>/<controller:\w+>' => '<module>/<controller>/index',

        ],
    ],

Upvotes: 1

Related Questions