You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP Klein Router在localhost URL下无法正常工作问题求助

问题:Klein Router在Apache本地环境路由失效,PHP内置服务器正常运行

我正在使用Klein Router开发基于MVC架构的原生PHP项目,遇到以下异常:

  • 通过http://localhost/myblog/home或http://localhost/myblog访问时,无法加载预期的页面内容
  • 使用php -S localhost:8000 -t /home/projects/myblog启动PHP内置服务器时,所有URL均可正常工作

现有代码

index.php

require_once __DIR__ . '/vendor/autoload.php';
$klein = new \Klein\Klein();

function r($method, $path, $handler) {
  global $klein;
  $klein->respond($method, $path, $handler);
}

// $klein->with('/myblog', function () use ($klein) {

  /*****************
   **** PUBLIC PAGES ROUTES
  ******************/
  r('GET', '/home', ['App\PublicPagesController', 'index']);
  r('GET', '/topics/[:topic_slug]', ['App\PublicPagesController', 'showTopicPosts']);


/*
  PAGE NOT FOUND ROUTES
*/ 
$klein->onHttpError(function ($code, $router) {
  switch ($code) {
    case 404:
      $router->response()->body(
        '404 Page...'
    );
    break;
    case 405:
      $router->response()->body(
          'You can\'t do that!'
      );
    break;
    default:
      $router->response()->body(
          'Oh no, a bad error happened that caused a '. $code
      );
  }
});

$klein->dispatch();

.htaccess

<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews -Indexes
    </IfModule>
    
    RewriteEngine On
    
    RewriteCond %{REQUEST_URI} !(/assets/) 
    RewriteCond $1 !^(robots.txt|ads.txt) 
    RewriteRule ^(.*)$ index.php [QSA,L]
</IfModule>

修复步骤

1. 补全路由前缀

项目部署在/myblog子目录下,Apache环境中请求URL包含/myblog前缀,但当前路由未匹配该前缀。取消注释index.php中的with代码块,将所有路由包裹在/myblog前缀下:

$klein->with('/myblog', function () use ($klein) {
  /*****************
   **** PUBLIC PAGES ROUTES
  ******************/
  r('GET', '/home', ['App\PublicPagesController', 'index']);
  r('GET', '/topics/[:topic_slug]', ['App\PublicPagesController', 'showTopicPosts']);
  // 添加首页路由
  r('GET', '/', ['App\PublicPagesController', 'index']);
});

2. 修正.htaccess重写规则

当前规则未适配子目录环境,修改后确保请求正确转发到index.php:

<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews -Indexes
    </IfModule>
    
    RewriteEngine On
    # 设置重写基准路径为项目子目录
    RewriteBase /myblog/
    
    RewriteCond %{REQUEST_URI} !(/assets/) 
    RewriteCond $1 !^(robots.txt|ads.txt) 
    # 将请求路径传递给index.php,供Klein解析
    RewriteRule ^(.*)$ index.php/$1 [QSA,L]
</IfModule>

3. 启用Apache重写模块

确保Apache已启用mod_rewrite:

  • Linux系统:执行sudo a2enmod rewrite,然后重启Apache服务sudo systemctl restart apache2
  • Windows(XAMPP/WAMP):打开Apache配置文件httpd.conf,取消注释LoadModule rewrite_module modules/mod_rewrite.so,重启Apache服务

4. 验证首页路由

添加r('GET', '/', ['App\PublicPagesController', 'index'])后,访问http://localhost/myblog即可匹配首页控制器。

内容的提问来源于stack exchange,提问作者Md. Amin Hossain

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 20:21:00