[英]How to rewrite the url in yii2
我已经在系统上安装了yii2。 默认网址是localhost/projectname/backend/web/
。
我希望前端的URL为http://localhost/projectname
,后端为http://localhost/projectname/admin
。 我正在按照第二个答案,即由该链接的despotbg给出Yii2 htaccess-如何完全隐藏前端/网络和后端/网络,但出现以下错误
无效的呼叫– yii \\ base \\ InvalidCallException设置只读属性:yii \\ web \\ Application :: request
请建议我如何删除此错误,以便我可以重写我的项目URL。 我在wamp服务器上工作
答案已更新,现在工作正常...
前端
修改文件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,
// ],
],
后端
修改文件backend / config / main.php:
....
'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,
// ],
],
阿帕奇(.htaccess与mod_rewrite)
在项目根目录(composer.json在其中)中创建文件.htaccess:
RewriteEngine On
# End the processing, if a rewrite already occurred
RewriteRule ^(frontend|backend)/web/ - [L]
# Handle the case of backend, skip ([S=1]) the following rule, if current matched
RewriteRule ^admin(/(.*))?$ backend/web/$2 [S=1]
# handle the case of frontend
RewriteRule .* frontend/web/$0
# Uncomment the following, if you want speaking URL
#RewriteCond %{REQUEST_FILENAME} !-f
#RewriteCond %{REQUEST_FILENAME} !-d
#RewriteRule ^([^/]+/web)/.*$ $1/index.php
后端\\ 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();
}
}
}
试试这个,希望对您有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.