如何使用.htaccess在Yii2框架中创建干净的URL


How to make clean URLs in Yii2 framework using .htaccess?

我正在尝试为我的网站制作干净的url,该网站是使用Yii2框架开发的,仅使用.htaccess。我知道我可以使用Yii2的urlmanager类。但由于一些特定的原因,我不能使用它,只想使用.htaccess来制作干净的url。

我想转换以下网址:Url='http://localhost:8090/index.php?r=site%2Fcontact'到Url='http://localhost:8090/contact'

提前谢谢。

首先,您必须更改yii2应用程序配置中的urlManager组件:

'urlManager' => [
    'enablePrettyUrl' => true,
    'showScriptName' => false,
]

showScriptName将从URL格式中删除index.php

enablePrettyUrl将提供漂亮的URL格式,如"http://localhost/contant"你想要)

其次,您需要在主机配置中设置URL重写规则。.htaccess(Apache)示例:

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

您可以在Yii2文档中阅读更多信息