PHP 除非在 index.php 中使用绝对路径,否则路由不起作用

PHP routing not working unless using an absolute path with index.php

使用 nikic/fast-route PHP 包用于 url 路由 :

PHP url 路由不起作用,除非我指定路由的整个路径,而不仅仅是路由的名称:

例如,为了为 /hello-world 创建一个路由,我必须指定整个路径:localhost/myProject/public/index.php/hello-world

$r->addRoute('GET', '/localhost/myProject/public/index.php/hello-world', function () {
        echo 'Hello World';
    });

是否需要在 .htaccess 文件中完成某些操作?

关于当前项目的细节:

我没有使用框架,而是 Patrick Louys 在 GitHub 上的无框架教程:https://github.com/PatrickLouys/no-framework-tutorial

我在 Fedora Linux 上使用 XAMPP 作为 Web 服务器

我的代码位于我的 /home 目录中,而 Web 服务器位于 /opt/lampp 中...我已经 link 用符号 link 编辑了它们:sudo ln -s /home/... /opt/lampp/htdocs(如果重要的话)...我知道教程依赖于 PHP 内置服务器 (php -S localhost:8000)

也许是错误的,但你必须写 ./helloworld

而不是 /helloworld

您必须将您的代码(文件)放入以下路径的 htdocs 文件夹中:

/opt/lampp/htdocs/

然后创建名为 hello-world 的文件夹,此文件夹必须以这种方式位于 htdocs 文件夹中:

/opt/lampp/htdocs/hello-world

接下来打开一个终端并像 root 用户一样访问,将目录更改为 hello-world 然后你必须像这样授予文件夹的权限:

chmod 667 hello-world -R

-R 用于授予文件夹hello-world 及其中所有文件的权限。就这样!现在,当您尝试 localhost/hello-world 时,您会看到您的项目正在运行!

注意:如果这不起作用,请尝试在路径 /opt/lampp/htdocs/ 之后的 htdocs 文件夹中创建一个名为 test.php 的 php 文件。该文件必须包含以下内容:

<h1><b><?php echo "hello wordl!"; ?></b></h1>

同样,您必须授予该文件权限 (chmod 667)。然后将其复制并粘贴到您的浏览器导航栏中:

localhost/test.php

您一定会在浏览器中看到一个大大的粗体hello world。

我的快速修复:

1- 在 public 目录中创建一个 .htaccess 文件。所有请求都将转发给 index.php

2- 添加一个函数来解析提交的整个 URL 以检索正确的 URI。基本上,该函数会修剪整个 url,例如 localhost/public/index.php/hello-world 和 returns /hello-world/hello-world 是我们的快速路由注册的路由,当我们的网络服务器 url 接收到这样的 url 时,将调用适当的控制器

来源(解释和代码示例):http://blogs.shephertz.com/2014/05/21/how-to-implement-url-routing-in-php/