【问题标题】:PHP routing not working unless using an absolute path with index.php除非使用带有 index.php 的绝对路径,否则 PHP 路由不起作用
【发布时间】:2018-01-02 08:39:26
【问题描述】:

使用 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 中...我已将它们与符号链接链接起来:sudo ln -s /home/... /opt/lampp/htdocs(如果重要的话)...我知道本教程依赖PHP内置服务器(php -S localhost:8000)

【问题讨论】:

    标签: php .htaccess routing fastroute


    【解决方案1】:

    我的快速修复:

    1- 在公共目录中创建一个.htaccess 文件。所有请求都会转发到index.php

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

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        【解决方案3】:

        您必须将您的代码(文件)放在此路径后面的 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。

        【讨论】:

          猜你喜欢
          • 2015-07-31
          • 2015-08-29
          • 1970-01-01
          • 2013-07-06
          • 1970-01-01
          • 2014-03-06
          相关资源
          最近更新 更多