创建Slim新项目时遭遇Slim\Exception\HttpNotFoundException错误求助
Hey there! No need to stress—this 404 error is super common when you're just getting started with Slim, and it's usually easy to fix. Let's break down what's happening and how to resolve it step by step.
What's Causing the Error?
The HttpNotFoundException with code 404 means Slim can't find a route that matches the URL you're trying to access. Looking at your index.php code, you've correctly defined a route for /hello/{name}, but there's probably a mismatch between the URL you're visiting and what Slim expects.
Step 1: Double-Check Your Access URL
Your project lives at C:\xampp\htdocs\MyApi, so your base URL must include the public directory (since that's where your Slim entry point index.php is located).
Instead of visiting something like http://localhost/MyApi or http://localhost/MyApi/hello/John, you need to use this exact URL:
http://localhost/MyApi/public/hello/John
Replace John with any name you want to test. Skipping the public part means Apache doesn't know to route the request to Slim, hence the 404.
Step 2: Verify Your .htaccess File
Slim relies on URL rewriting to route requests correctly, and that requires a .htaccess file in your public folder. If this file is missing or misconfigured, Apache can't forward requests to index.php.
Create a file named .htaccess in C:\xampp\htdocs\MyApi\public with this content:
RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^ index.php [QSA,L]
Also, make sure Apache's mod_rewrite module is enabled in XAMPP (it's usually on by default, but if not, uncomment the line LoadModule rewrite_module modules/mod_rewrite.so in Apache's httpd.conf file).
Step 3: Test a Simple Root Route (Optional)
To confirm your core Slim setup is working, add a basic root route to your index.php right before $app->run();:
$app->get('/', function (Request $request, Response $response) { $response->getBody()->write("Hey, Slim is up and running!"); return $response; });
Then visit http://localhost/MyApi/public/—if you see the message, your Slim installation is good, and the issue was just the incorrect URL for your /hello/{name} route.
Step 4: Confirm Apache's Document Root
Double-check that XAMPP's Apache is using htdocs as its document root (it should be default). If you've changed this setting, ensure it still points to C:\xampp\htdocs so your MyApi project is accessible.
Wrap-Up
9 times out of 10, this error boils down to a wrong URL or missing .htaccess file. Start with the URL check first—it's the simplest fix. Once you get that working, you can explore setting up a virtual host later to avoid typing public in your URL, but let's nail the basics first!
内容的提问来源于stack exchange,提问作者Prosenjith Roy

