Current Location: Home> Latest Articles> How to Properly Configure defaultAction After Enabling enablePrettyUrl in Yii2

How to Properly Configure defaultAction After Enabling enablePrettyUrl in Yii2

gitbox 2025-07-28

Introduction to enablePrettyUrl in Yii2

Before configuring defaultAction, it's important to understand the enablePrettyUrl property in Yii2. This property transforms traditional parameter-based URLs (like ?id=xx&name=yy) into cleaner and more readable URL formats. For example, it rewrites index.php?r=site%2Fabout&id=1 as site/about/1. This URL optimization enhances user experience and is beneficial for search engine optimization (SEO).

In Yii2 configuration files, you typically enable this feature with the following code:

'urlManager' => [
    'class' => 'yii\web\UrlManager',
    'enablePrettyUrl' => true,
    'showScriptName' => false,
],

Here, 'enablePrettyUrl' => true enables pretty URLs, and 'showScriptName' => false hides the index.php filename.

How to Change the Default View in Yii2

Yii2 uses the defaultRoute property to control the default view. After setting it, visiting the website root will directly display the specified page. For example, the following configuration sets the default view to site/index:

return [
    // ...
    'defaultRoute' => 'site/index',
    // ...
];

Setting the Default Access Page via defaultAction

If you want to specify the default action for a controller, use the defaultAction property. Here is an example configuration:

'urlManager' => [
    'class' => 'yii\web\UrlManager',
    'enablePrettyUrl' => true,
    'showScriptName' => false,
    'rules' => [
        '' => 'site/index',
    ],
    'defaultAction' => 'site/index',
],

Here, the empty string '' represents the website root, which is mapped to the site/index page.

The 'rules' key defines custom URL routing rules, which you can expand as needed. For example:

'rules' => [
    '' => 'site/index',
    'login' => 'site/login',
    'admin' => 'admin/default/index',
],

Notes After Modifying Configuration

After modifying your configuration, it is recommended to restart your Apache or Nginx server to ensure Yii2 applies the new settings properly. Proper default page and routing configurations not only improve loading speed but also significantly benefit SEO.

Summary

Properly configuring enablePrettyUrl and defaultAction is a key step in optimizing user experience and search engine rankings in Yii2 development. Using the examples provided, you can easily adjust your default pages and routing rules to build a clear and efficient application structure.