Slim Framework v3 API URL重写求助:移除api.php后缀
Hey there! Let's get that api.php suffix removed from your Slim Framework v3 API URL. I'll walk you through the exact steps to make this work, since your current configs aren't hitting the mark.
Step 1: Make Sure mod_rewrite is Enabled
First things first—Apache's mod_rewrite module needs to be turned on, and your server needs to allow .htaccess overrides:
- Check your Apache config file (usually
httpd.conforapache2.conf) forLoadModule rewrite_module modules/mod_rewrite.so—uncomment it if it's commented out. - In your virtual host configuration for
apps.example.com, setAllowOverride Allfor the/app/v1/myappdirectory (or the root if that's where your app lives). This lets.htaccessrules take effect. - Restart Apache after making these changes.
Step 2: Correct .htaccess Configuration
Place this .htaccess file in the same directory as your api.php file (that's /app/v1/myapp/ based on your URL):
RewriteEngine On # Force HTTPS (adjust the domain to match your setup) RewriteCond %{HTTPS} off RewriteRule ^(.*)$ https://apps.example.com/app/v1/myapp/$1 [L,R=301] # Rewrite requests to remove api.php RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ api.php/$1 [L]
Let me break this down:
- The first two lines force all traffic to HTTPS (skip this if you don't need it, but it's good practice).
- The next two
RewriteCondlines make sure we only rewrite requests that aren't pointing to an existing file or directory (so static assets like CSS/JS aren't affected). - The final rule forwards all requests to
api.php/{your-path}, which lets Slim handle the routing without showingapi.phpin the URL.
Step 3: Set Slim's Base Path
In your api.php file, when initializing the Slim app, set the correct basePath to match your app's URL structure. This helps Slim resolve routes correctly:
$app = new Slim\App([ 'settings' => [ 'determineRouteBeforeAppMiddleware' => true, 'basePath' => '/app/v1/myapp', // Add other Slim settings here as needed ] ]);
Step 4: Test and Troubleshoot
- Clear your browser's cache first—old 301 redirects might be cached and causing issues.
- Make sure your Slim routes are set up without
api.phpin them. For example, your sign-in route should look like this:$app->post('/signin', function ($request, $response, $args) { // Your sign-in logic here return $response->withJson(['status' => 'success']); }); - Check if there are any other
.htaccessfiles in parent directories (like/app/v1/or the root) that might be overriding your rules. If so, adjust those or make sure your child directory's rules take precedence.
That should do it! You should now be able to access https://apps.example.com/app/v1/myapp/signin without the api.php suffix.
内容的提问来源于stack exchange,提问作者kasar sandeep

