php - Yii2 Static Pages Not Found

I've created a view in views/sites/example.php

<?php   
use yii\helpers\Html;   
?>   
<?= Html::encode($message) ?>  

Then in SiteController.php I have added

    public function actionExample($message = 'Hello')   
    {   
        return $this->render('example', ['message' => $message]);   
    }  

In main.php, the urlManager is configured

        'urlManager' => [
            'enablePrettyUrl' => true,
            'showScriptName' => false,
            'rules' => array(
                '<controller:\w+>/<id:\d+>' => '<controller>/view',
                '<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>',
                '<controller:\w+>/<action:\w+>' => '<controller>/<action>',
            ),
        ],

when I try to access the page at localhost/example, I get a 404. What have I missed??

Answer

Solution:

In rules section of urlManager part of code there are rules for which URL is checked to determine controller, action etc.

Because your action is in SiteController it can be accessed by //localhost/site/example/ url (rule '<controller:\w+>/<action:\w+>' => '<controller>/<action>').

So to make your action accessible via //localhost/example/ url another rule should be added to rules section.

If you add 'example' => 'site/example', to rules your action will be accessible on desired URL.

There is also a guide on https://www.yiiframework.com/doc/guide/2.0/en/runtime-routing so you can better understand routing in yii2.

Source