Search code examples
phpapache.htaccessslim-3

PHP Slim 3 .htaccess and index.php not working in subdirectory


I have a simple PHP Slim 3 project. Everything works fine and dandy when .htaccess and index.php are in root directory but I want to keep them in subdirectory "public". When I have them there, I get Error 404. It is not a mandatory thing but I want to keep everything in structure and know what is causing the error or how to fix it for future reference.

Project structure

root
 app
  controllers
 bootstrap
 logs
 public
  css
  js
 resources
 vendor

.htaccess

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

index.php

<?php
// Require application bootstrap
require __DIR__ . '/../bootstrap/app.php';

// Run Slim
$app->run();

Note: project is in remote server running on Apache


Solution

  • based on your file .htaccess should be something like this

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

    adding the public redirects it to the public folder and for the index.php

    index.php

    should look like something like this when put into the public folder

    <?php
    // Require application bootstrap
    require dirname(__DIR__). '/bootstrap/app.php';
    
    // Run Slim
    $app->run()
    

    I hope this helps

    Please also note with this simple help, there could be security concern as @Eric suggest in my comment, so extra work can be done, this is just to solve your current question, so as to reduce any headache it may be giving you

    You can help address such security issue if you have access to your Virtual apache conf file, you can simply point your documentRoot to your public file and place your you previous .htaccess file in the public folder along side the index.php but this time your .htaccess uses your previous configuration

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

    when you don't have access lets say on a shared hosting with cpanel simply put your index.php file and .htaccess in your public_html, and put the rest of your application files and folder aside the necessary ones that need to be in the public_html folder such as your css, js and images.

    I hope this was much more helpful