Slim Framework always return 404 Error
I found this post while googling "slimframework 404". The post led me to a solution to my problem.
The Problem
I set up a site with the Slim framework using Composer and create an index.php with the following example code form slimframework.com:
<?php
$app = new \Slim\Slim();
$app->get('/hello/:name', function ($name) {
echo "Hello, $name";
});
$app->run();
Then I try to access the page using http://localhost/hello/bob
. I get back a 404 Page Not Found page.
I was able to get to access the page using http://localhost/index.php/hello/bob
.
The Solution
I found the solution by looking at /vendor/slim/.htaccess
(included w/ Composer Slim install) and the URL Rewriting section of the Slim framework documentation.
I added a copy of the /vendor/slim/.htaccess
file to the same folder as my index.php file. The contents of the file are:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [QSA,L]
Now I can access the page using http://localhost/hello/bob
.
Problem is solved!
My apache is actually normal, and the .htaccess file provided earlier also normal.
The clue is the URL that I used. Previously I used the invalid URL, thus it returned the 404 page error. I just realized it when I Tried to access the newer GET URL via browser with this one;
http://localhost/dev/index.php/getUsers/user1
and now that works!
I just realized it once I found these statements;
If Slim does not find routes with URIs that match the HTTP request URI, Slim will automatically return a 404 Not Found response.
If Slim finds routes with URIs that match the HTTP request URI but not the HTTP request method, Slim will automatically return a 405 Method Not Allowed response with an Allow: header whose value lists HTTP methods that are acceptable for the requested resource.