htaccess 用于使用 phplegue 路由的自定义 url 路由

htaccess for custom url routing using thephplegue route

我是 PHP 的新手。我在我的应用程序中使用 packagist.org 中的 league/route 进行路由,我的根目录中有一个 public 文件夹,其中有一个 index.php 文件用于路由,如下所示。

require_once '../vendor/autoload.php';

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

$router = new League\Route\RouteCollection;

$router->addRoute('GET', '/acme', function (Request $request, Response $response) {
    echo "here";

    return "working";
});

$dispatcher = $router->getDispatcher();

$response = $dispatcher->dispatch('GET', '/acme');

$response->send();

.htaccess 文件位于根文件夹中,如下所示

RewriteEngine On

RewriteBase /HMT/public

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^ index.php [QSA,L]

问题是当我 运行 http://localhost/HMT/acme 没有任何显示。我尝试在 public/index.php 文件的每一行之后添加一个 echo 语句,并注意到下面的行不起作用。我也认为我的 .htaccess 可能是问题所在??

$dispatcher = $router->getDispatcher();

感谢您的帮助,谢谢。

这里有几个问题。

您似乎关闭了错误报告,或者您会看到某种错误。

将以下代码添加到 index.php.

的顶部
error_reporting(-1);
ini_set('display_errors', 'On');

您的 .htaccess 实际上应该在您的 public 目录中,并且格式如下。

RewriteEngine On
RewriteBase /HMT/public
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond  !\.(html)
RewriteRule ^(.*)$ index.php?/ [L,QSA]

然后根据您提供的信息,如果您访问 http://localhost/HMT/public 那么一切都应该正常工作。

根据您可能收到的任何错误以及您使用的 league/route 的版本,可能需要采取进一步的步骤来确保将请求 URI 正确发送到调度程序。