兩步驟完成美觀網址
1. 設定 urlManager (config/main.php)
<?php
return [
'components' => [
'urlManager' => [
'urlFormat' => 'path', // 使用 PATH 格式 (非 GET 參數)
'showScriptName' => false, // 關鍵:隱藏 index.php
'enablePrettyUrl' => true, // 啟用美觀網址 (Yii 2.0+ 參數名)
'rules' => [
'<controller:\w+>/<id:\d+>' => '<controller>/view',
'<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>',
'<controller:\w+>/<action:\w+>' => '<controller>/<action>',
// 自訂規則範例
'post/<id:\d+>' => 'post/view',
'archive/<year:\d{4}>/<month:\d{2}>' => 'post/archive',
],
],
],
];
?>
2. 設定 Web 伺服器 Rewrite 規則
Apache (.htaccess 放於網站根目錄)
Options +FollowSymLinks
IndexIgnore */*
RewriteEngine on
# 真實存在的檔案/目錄直接存取
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# 其他請求導向 index.php
RewriteRule . index.php
Nginx (server 區塊內)
location / {
try_files $uri $uri/ /index.php$is_args$args;
}
# 或舊版寫法
location / {
if (!-f $request_filename) {
rewrite ^/(.*)$ /index.php/$1 last;
}
}
IIS (web.config)
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<rewrite>
<rules>
<rule name="Yii2 Pretty URL" stopProcessing="true">
<match url="^(.*)$" />
<conditions logicalGrouping="MatchAll">
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
</conditions>
<action type="Rewrite" url="index.php/{R:1}" />
</rule>
</rules>
</rewrite>
</system.webServer>
</configuration>
驗證是否生效
| 原始網址 | 美觀網址 | 對應路由 |
| `/index.php?r=site/index` | `/site/index` 或 `/` | `site/index` |
| `/index.php?r=post/view&id=123` | `/post/123` | `post/view` |
| `/index.php?r=user/profile&name=john` | `/user/profile/name/john` | `user/profile` |
常見問題排查
- 404 Not Found:Rewrite 模組未啟用、.htaccess 權限/位置錯誤、規則語法錯誤
- 網址仍顯示 index.php:`showScriptName` 未設 `false`、快取未清除
- CSS/JS/圖片 404:靜態資源被 Rewrite 導向 index.php,需確認 `RewriteCond !-f` 生效
- 子目錄部署:`RewriteBase /subdir/` 或 Nginx `location /subdir/` 調整
進階:RESTful API 規則
<?php
'rules' => [
// REST 風格
['class' => 'yii\rest\UrlRule', 'controller' => 'user'],
// 或手動定義
'POST users' => 'user/create',
'GET users' => 'user/index',
'GET users/' => 'user/view',
'PUT users/' => 'user/update',
'DELETE users/' => 'user/delete',
],
?>