Search code examples
php.htaccessslim

Slim Framework remove public folder in URL


There is a similar question here, but I still need to include the public folder in my URL.

Current URL: https://my-domain.com/api/public/pins

What I want: https://my-domain.com/api/pins

This is my project structure

enter image description here

As you can see, I have 2 .htaccess files, where and what should I write a .htaccess script to redirect the public folder?

.htaccess in public folder

# Redirect to front controller
RewriteEngine On

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

.htaccess in root folder

RewriteEngine on
RewriteRule ^$ public/ [L]
RewriteRule (.*) public/$1 [L]

Solution

  • Here is an example to make an "internal redirect" to the public directory:

    RewriteEngine on
    RewriteRule ^$ public/ [L]
    RewriteRule (.*) public/$1 [L]
    

    The .htaccess in the public/ directory could contain this content:

    # Redirect to front controller
    RewriteEngine On
    # RewriteBase /
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [QSA,L]
    

    In Slim 4: Make sure to set the correct Slim basePath.

    $app->setBasePath('/api');
    

    See documentation: https://www.slimframework.com/docs/v4/start/web-servers.html#apache-configuration

    In Slim 3: Patch the Slim Environment as follows.

    $container['environment'] = function () {
        $scriptName = $_SERVER['SCRIPT_NAME'];
        $_SERVER['REAL_SCRIPT_NAME'] = $scriptName;
        $_SERVER['SCRIPT_NAME'] = dirname(dirname($scriptName)) . '/' . basename($scriptName);
    
        return new Slim\Http\Environment($_SERVER);
    };
    

    Example