Yii2 将带有查询字符串的 URL 重写为 SEO
Yii2 rewrite URLs with query string to be SEO
我所拥有的可以在 YiiURL 中做出漂亮的
example.com/readings/view?BookID=9955
首先,readings
是我的默认控制器,所以我不希望它的操作以其名称作为前缀,即:
example.com/view?BookID=9955
其次,我需要忽略 ?BookID=
成为:
example.com/view/9955
我还有书页:
example.com/readings/view?BookID=9955&start=2
我需要它
example.com/readings/view/9955/2
我的 URL 管理器配置是:
'defaultRoute' => 'readings/index',
//'catchAll' => ['site/offline'],
'components' => [
'urlManager' => [
'class' => 'yii\web\UrlManager',
// Disable index.php
'showScriptName' => false,
// Disable r= routes
'enablePrettyUrl' => true,
'rules' => array(
'<controller:\w+>/<id:\d+>' => '<controller>/view',
'<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>',
'<controller:\w+>/<action:\w+>' => '<controller>/<action>',
),
],...
和.htaccess
:
RewriteEngine on
# If a directory or a file exists, use it directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# Otherwise forward it to index.php
RewriteRule . index.php
您需要配置规则配置以反映您希望它执行的操作。
要将 example.com/view?BookID=9955 转换为 example.com/view/9955 你需要:
1) 添加以下规则:
'view/<BookID:\d+>' => 'readings/view'
2) 确保您的控制器操作设置为接受 BookID 参数:
public function actionView($BookID)
{
...
}
我所拥有的可以在 YiiURL 中做出漂亮的
example.com/readings/view?BookID=9955
首先,readings
是我的默认控制器,所以我不希望它的操作以其名称作为前缀,即:
example.com/view?BookID=9955
其次,我需要忽略 ?BookID=
成为:
example.com/view/9955
我还有书页:
example.com/readings/view?BookID=9955&start=2
我需要它
example.com/readings/view/9955/2
我的 URL 管理器配置是:
'defaultRoute' => 'readings/index',
//'catchAll' => ['site/offline'],
'components' => [
'urlManager' => [
'class' => 'yii\web\UrlManager',
// Disable index.php
'showScriptName' => false,
// Disable r= routes
'enablePrettyUrl' => true,
'rules' => array(
'<controller:\w+>/<id:\d+>' => '<controller>/view',
'<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>',
'<controller:\w+>/<action:\w+>' => '<controller>/<action>',
),
],...
和.htaccess
:
RewriteEngine on
# If a directory or a file exists, use it directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# Otherwise forward it to index.php
RewriteRule . index.php
您需要配置规则配置以反映您希望它执行的操作。 要将 example.com/view?BookID=9955 转换为 example.com/view/9955 你需要:
1) 添加以下规则:
'view/<BookID:\d+>' => 'readings/view'
2) 确保您的控制器操作设置为接受 BookID 参数:
public function actionView($BookID)
{
...
}