PHP Composer报404错误:请求URL未找到问题求助
Fixing 404 Error with Slim 3 on Apache
Alright, let's troubleshoot that 404 error you're hitting when accessing localhost/hello/foo with Slim 3 and Apache. Here's a step-by-step breakdown to get your endpoint working:
1. Verify Your File Structure & Apache Modules
First, double-check your core setup:
- Make sure your
index.phpis located in/var/www/html/hello/(since you're accessinglocalhost/hello/...). If it's directly in/var/www/html/, your target URL should belocalhost/fooinstead. - Ensure your
index.phphas complete Slim initialization code (your snippet was truncated). A minimal working example looks like this:<?php use \Psr\Http\Message\ServerRequestInterface as Request; use \Psr\Http\Message\ResponseInterface as Response; // Adjust the path to autoload.php based on your composer setup require 'vendor/autoload.php'; $app = new Slim\App(); // Define your route to match your desired URL $app->get('/foo', function (Request $request, Response $response) { $response->getBody()->write("Hello from Foo!"); return $response; }); $app->run(); - Enable Apache's
mod_rewritemodule (critical for Slim's URL routing) with these commands:sudo a2enmod rewrite sudo systemctl restart apache2
2. Configure .htaccess & Apache Site Settings
Slim relies on URL rewriting to route all requests to index.php, so you need a proper .htaccess file:
- Create (or update)
.htaccessin/var/www/html/hello/with this content:RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^ index.php [QSA,L] - Update your Apache site configuration (usually at
/etc/apache2/sites-available/000-default.conf) to allow.htaccessoverrides. Find the<Directory /var/www/html>block and modify it to:<Directory /var/www/html> Options Indexes FollowSymLinks MultiViews AllowOverride All Require all granted </Directory> - Restart Apache again to apply changes:
sudo systemctl restart apache2
3. Confirm Composer Dependencies Are Installed
Head to your /var/www/html/hello/ directory and run:
composer install
This ensures the slim/slim package and all required dependencies are installed (you should see a vendor directory after this completes).
4. Check Route-to-URL Matching
A common mistake is mismatched routes and URLs:
- If your
index.phpis in/var/www/html/hello/, the routes you define are relative tolocalhost/hello/. So a route$app->get('/foo', ...)maps directly tolocalhost/hello/foo(which is what you're trying to access). - If you had defined a route like
$app->get('/hello/foo', ...), you'd need to accesslocalhost/hello/hello/foo—which doesn't exist, hence the 404.
内容的提问来源于stack exchange,提问作者Frakcool
相关产品推荐
相关产品推荐

