Setting Up Yii URL Manager for Clean, SEO‑Friendly URLs
Learn how to enable Yii's URL manager to drop index.php, create readable routes, and avoid common pitfalls that cause 404s or duplicate content.
03 Aug 2026, 01:29 UTC

Useful answer
Enable Yii’s URL manager to drop the entry script from the address bar and map readable paths to controller actions. This improves SEO and user experience while keeping the application functional.
Configuration example
In config/web.php (basic application template) add or modify the urlManager component:
'components' => [
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
// specific → generic order
'/' => '/view',
'//' => '/',
'/' => '/',
],
],
],
How the mechanism works
When enablePrettyUrl is true, Yii treats the incoming request path as a candidate for matching against the rules array. The first rule whose regular expression matches the path is used to derive the route (controller/action) and any parameters. With showScriptName set to false, the URL generator omits index.php when creating links, so the browser sees only the clean path.
Limits and performance considerations
Each request requires the URL manager to evaluate the rules sequentially until a match is found. A large or poorly ordered rule set increases CPU overhead. To keep impact low:
- Place the most specific patterns first.
- Avoid overly permissive patterns like
.*that force the engine to scan many rules. - If you have dozens of rules, consider grouping them in a custom URL rule class or using module‑specific managers.
Common mistakes and how to avoid them
- Forgetting
showScriptName => false– URLs retainindex.php(e.g.,/index.php/site/view/42). Fix: set the option as shown above. - Incorrect rule ordering – a generic rule like
'/' => '/'placed before the/\d+rule consumes URLs such as/site/view/42and treats42as an action, leading to a 404. Fix: order rules from specific to generic. - Inconsistent trailing slashes –
/site/view/42and/site/view/42/are seen as different URLs, creating duplicate content. Choose one style (usually without trailing slash) and enforce it via a canonical rule or web‑server redirect.
Verification steps (no output claimed)
After saving the configuration:
- Access a URL like
http://your-host/site/view/42in a browser. - Confirm the address bar shows exactly that path (no
index.php). - Check that the response is rendered by
SiteController::actionViewwith$id = 42(you can add a temporaryvar_dump($id); exit;to see the value). - Test an invalid pattern, e.g.,
http://your-host/unknown/123, and verify you receive a 404 Not Found. - Optionally, run
curl -I http://your-host/site/view/42and look forHTTP/1.1 200 OKin the headers.
If changes do not appear, clear the runtime cache (rm -rf @runtime/cache or delete the cache folder under the runtime directory) to force Yii to reload the URL manager configuration.
0 replies
A thoughtful contribution can make all the difference. Be the first to share one.