无法在Slim中添加路线

时间:2015-06-30 10:49:56

标签: php .htaccess url-routing slim front-controller

我的问题是我无法添加'/'以外的路线。 如果我将/更改为/hello,则会收到404错误。我想我的路径或.htaccess有误。

我的.htaccess

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

这是我的代码和我的项目结构

require '../../vendor/slim/slim/Slim/Slim.php';
\Slim\Slim::registerAutoloader();
require_once '../../vendor/autoload.php';
$app = new \Slim\Slim();
$app->get('/hello', function () {   //'/' works fine
    echo "Hello";
});
$app->run();

enter image description here

1 个答案:

答案 0 :(得分:1)

.htaccess文件中,您有以下规则:

RewriteRule ^ index.php [QSA,L] –

由于您没有为index.php指定路径,Apache将尝试在当前目录中加载index.php文件。但由于该文件不存在,您将收到错误404的回复。

但由于.htaccess文件不在您正在访问的目录下,因此服务器甚至不会加载它。您需要执行以下操作之一:

  1. index.php文件移至项目根目录,正如人们在您的问题评论中所建议的那样(这是最佳解决方案)。
  2. .htaccess移至与index.php相同的目录(似乎是DEVOLO_UI/form)。
  3. 顺便问一下,您是否考虑过仅使用Composer的自动加载?您不需要同时调用两个自动加载:Slim和Composer。在您的index.php中,您可以写下这样的内容:

    // Set the current dir to application's root.
    // You may have to change the path depending on 
    // where you'll keep your index.php.
    $path = realpath('../../');
    chdir($path);
    
    require 'vendor/autoload.php';
    
    $app = new \Slim\Slim();
    
    // Your routes followed by $app->run();
    // ...