如何将XAMP中htdocs子文件夹设为CakePHP项目根目录?
CakePHP子目录部署路由问题解决方法
我用XAMPP搭建本地开发环境,把项目放在htdocs的子目录myProject下,访问路径为localhost/myProject/index.php。但框架现在把localhost当成项目根目录,访问localhost/myProject/controller/action时,会错误地将myProject识别为要查找的控制器,导致路由失效。
当前.htaccess配置
项目根目录.htaccess
<IfModule mod_rewrite.c> RewriteEngine on RewriteRule ^$ webroot/ [L] RewriteRule (.*) webroot/$1 [L] RewriteBase /bakesystem #Rewrite everything to https RewriteEngine On RewriteCond %{HTTPS} !=on RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301] </IfModule>
webroot目录.htaccess
<IfModule mod_rewrite.c> RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^ index.php [L] #Rewrite everything to https - disabled on test #RewriteEngine On #RewriteCond %{HTTPS} !=on #RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301] </IfModule>
解决步骤
1. 修正项目根目录的RewriteBase
当前RewriteBase /bakesystem路径错误,需改为项目对应的子目录路径,同时合并重复的RewriteEngine配置:
<IfModule mod_rewrite.c> RewriteEngine on RewriteBase /myProject # 重定向请求到webroot目录 RewriteRule ^$ webroot/ [L] RewriteRule (.*) webroot/$1 [L] # 强制跳转HTTPS(按需启用) RewriteCond %{HTTPS} !=on RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301] </IfModule>
2. 设置CakePHP的项目基准路径
打开config/app.php,找到App配置块,添加baseUrl参数指定子目录:
'App' => [ 'namespace' => 'App', 'encoding' => env('APP_ENCODING', 'UTF-8'), 'defaultLocale' => env('APP_DEFAULT_LOCALE', 'en_US'), 'baseUrl' => '/myProject', // 新增此行指定项目子目录 // 其他原有配置保持不变 ]
3. 确认webroot目录.htaccess配置
webroot的配置无需修改RewriteBase,如需启用HTTPS,取消注释相关代码时注意不要重复开启RewriteEngine:
<IfModule mod_rewrite.c> RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^ index.php [L] # 取消以下两行注释可开启HTTPS # RewriteCond %{HTTPS} !=on # RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301] </IfModule>
4. 重启XAMPP的Apache服务
修改所有配置后,必须重启Apache服务,确保新的规则和项目配置生效。
内容的提问来源于stack exchange,提问作者J.B.J.
相关产品推荐
相关产品推荐

