404使用SLIM框架路由时出错

时间:2015-07-27 17:15:18

标签: php apache .htaccess mod-rewrite slim

我在http://www.example.com/API/

中有我的SLIM PHP应用程序

我的index.php中有路由,如此:

$app->get('/getstudents', function() use($app) {
    $db = new DbHandler();
    $result = $db->getAllStudents();

    if ($result === false) {
        echo "Failed to fetch";
    } else {
        echo json_encode($result);
    }
});

$app->run();

当我尝试使用curl http://example.com/API/getstudents的网址时,我收到错误在此服务器上找不到请求的网址/ API / getstudents。

如果我使用curl http://example.com/API/index.php/getstudents,则会按预期返回学生列表。我已经用Google搜索并了解这可能是因为.htaccess文件和/或虚拟主机设置。

因此,我已将.htaccess的{​​{1}}副本复制到API文件夹,因此它与API/vendor/slim/slim/.htaccess位于同一文件夹中。在这个文件中我有:

index.php

这没有运气。我是否需要更改API目录和API / vendor / slim / slim /中的# Some hosts may require you to use the `RewriteBase` directive. # If you need to use the `RewriteBase` directive, it should be the # absolute physical path to the directory that contains this htaccess file. # # RewriteBase / RewriteEngine On RewriteBase /API/ RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^ index.php [QSA,L] 文件的内容?

我也不完全确定我需要对我的虚拟主机文件做些什么。在/ etc / apache2 / sites-available中我正在编辑 example.com.conf ,内容是:

.htaccess

有人可以给我一些指示我可能在这里做错的事吗?谢谢!

3 个答案:

答案 0 :(得分:1)

要做的第一件事:

更改您的路线:

$app->get('/API/getstudents', function() use($app) {

如果不起作用,请执行以下操作:

解决这个问题,让你的路线像这样:

$app->get('/api/book', function () {
    header('Content-Type: application/json; charset=utf-8');
    $data = Book::getBookObjects();
    echo $data;
});
  

这是我的一个项目的示例,您可以使用API​​而不是api。

.htaccess文件:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ index.php [QSA,L]

我项目的工作树是这样的:

Project Folder -> public -> .htaccess, index.php

Project Folder -> api -> book

调整您的代码:

$app->get('/api/getstudents', function() use($app) {
    $db = new DbHandler();
    $result = $db->getAllStudents();
    if ($result === false) {
        echo "Failed to fetch";
    } else {
        echo json_encode($result);
    }
});

$app->run();

答案 1 :(得分:0)

尝试在API位置创建.htaccess文件,其中index.php文件包含数据

RewriteEngine On 
RewriteCond %{REQUEST_FILENAME} !-f 
RewriteRule ^(.*)$ %{ENV:BASE}index.php [QSA,L]

答案 2 :(得分:0)

this answer在Slim论坛上所述:

如果您的Slim应用不在服务器根路径(http://<host>/[index.php])上,则必须说明路径的完整路径。

让我们以以下网址为例:http://<host>/staging/

那么您有两个选择可以实现我们的目标:

  • 陈述您所有路线$app->get('/staging/', handler);中的路径,依此类推,或者
  • 在创建应用$app->SetBasePath('/staging');后一次声明它
相关问题