【问题标题】:htaccess for custom url routing using thephplegue routehtaccess 使用 phplegue 路由进行自定义 url 路由
【发布时间】:2016-01-09 01:02:45
【问题描述】:

我是 PHP 新手。我正在使用来自 packagist.org 的联盟/路由在我的应用程序中进行路由,并且我的根目录中有一个公用文件夹,其中有一个 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();

感谢您的帮助,谢谢。

【问题讨论】:

  • 您应该会收到一条错误消息。尝试在索引文件的开头添加:ini_set('display_errors',1); 以进行调试。

标签: php .htaccess url-rewriting url-routing


【解决方案1】:

所以这里有几个问题。

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

将以下代码添加到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 $1 !\.(html)
RewriteRule ^(.*)$ index.php?/$1 [L,QSA]

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

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

【讨论】:

  • 谢谢。如果我访问“/acme”,我收到错误“内部服务器错误”,当我访问“/”时,我收到错误“可捕获的致命错误:传递给 League\Route\RouteCollection::getDispatcher() 的参数 1 必须是Psr\Http\Message\ServerRequestInterface 的实例,没有给出。”
  • 对,这是因为您的 index.php 文件设置为使用第 1 版的联赛/路线,但您实际上安装了未完成的第 2 版
猜你喜欢
  • 2016-05-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-10
  • 1970-01-01
  • 2013-12-08
  • 1970-01-01
相关资源
最近更新 更多