Php 如何在yii2中重写url
我已经在我的系统上安装了yii2。默认url是Php 如何在yii2中重写url,php,yii,wamp,yii2,yii-url-manager,Php,Yii,Wamp,Yii2,Yii Url Manager,我已经在我的系统上安装了yii2。默认url是localhost/projectname/backend/web/ 我希望我的url应该是http://localhost/projectname用于前端和http://localhost/projectname/admin用于后端。我遵循的第二个答案,即由despotbg给出的这个链接,但我得到以下错误 无效调用–yii\base\InvalidCallException设置只读属性:yii\web\Application::request 请建
localhost/projectname/backend/web/
我希望我的url应该是http://localhost/projectname
用于前端和http://localhost/projectname/admin
用于后端。我遵循的第二个答案,即由despotbg给出的这个链接,但我得到以下错误
无效调用–yii\base\InvalidCallException设置只读属性:yii\web\Application::request
请建议我如何删除此错误,以便重写我的项目url。我正在wamp服务器上工作backend\config\main.php
// backend, under components array
'request'=>[
'class' => 'common\components\Request',
'web'=> '/backend/web',
'adminUrl' => '/admin'
],
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
],
在common\components上创建request.php文件
<?php
namespace common\components;
class Request extends \yii\web\Request {
public $web;
public $adminUrl;
public function getBaseUrl(){
return str_replace($this->web, "", parent::getBaseUrl()) . $this->adminUrl;
}
/*
If you don't have this function, the admin site will 404 if you leave off
the trailing slash.
E.g.:
Wouldn't work:
site.com/admin
Would work:
site.com/admin/
Using this function, both will work.
*/
public function resolvePathInfo(){
if($this->getUrl() === $this->adminUrl){
return "";
}else{
return parent::resolvePathInfo();
}
}
}
答案已更新,现在可以正常工作了
前端
修改文件frontend/config/main.php:
....
'components' => [
....
'request'=>[
'baseUrl'=>'/projectname',
],
'urlManager'=>[
'scriptUrl'=>'/projectname/index.php',
],
// use the following, if you want to enable speaking URL for the frontend
// 'urlManager' => [
// 'enablePrettyUrl' => true,
// 'showScriptName' => false,
// ],
],
....
'components' => [
....
'request'=>[
'baseUrl'=>'/projectname/admin',
],
'urlManager'=>[
'scriptUrl'=>'/projectname/admin/index.php',
],
// use the following, if you want to enable speaking URL for the backend
// 'urlManager' => [
// 'enablePrettyUrl' => true,
// 'showScriptName' => false,
// ],
],
后端
修改backend/config/main.php文件:
....
'components' => [
....
'request'=>[
'baseUrl'=>'/projectname',
],
'urlManager'=>[
'scriptUrl'=>'/projectname/index.php',
],
// use the following, if you want to enable speaking URL for the frontend
// 'urlManager' => [
// 'enablePrettyUrl' => true,
// 'showScriptName' => false,
// ],
],
....
'components' => [
....
'request'=>[
'baseUrl'=>'/projectname/admin',
],
'urlManager'=>[
'scriptUrl'=>'/projectname/admin/index.php',
],
// use the following, if you want to enable speaking URL for the backend
// 'urlManager' => [
// 'enablePrettyUrl' => true,
// 'showScriptName' => false,
// ],
],
Apache(.htaccess和mod_重写)
在项目根目录中创建文件.htaccess(其中composer.json为):
这很可能与yii无关,而是与虚拟主机设置有关。我会在wamp问题页面上问这个问题。我清理了你的语法(包装你的示例URL让其他人知道它不是链接),但是你可能想发布更多的代码细节,以便其他读者可以帮助你。根据您的问题和其他评论,我还将此标记为wamp。