Custom 404 page with Silex not rendered in prod configuration

Didier Ghys picture Didier Ghys · Aug 13, 2012 · Viewed 8.5k times · Source

I am struggling a little bit while trying to display a custom 404 error page using the Silex micro-framework.

My project is configured as follows:

  • got an index.php page to run in production mode, loading a prod.php configuration file
  • got an index_dev.php to run in debug mode. It uses also the prod.php configuration file, but some settings gets overridden by a dev.php file, like $app['debug'] being set to true.

So basically the configuration is the same.

I have defined an error handler as follows:

$app->error(function (\Exception $e, $code) use ($app) {

    // commented for testing purposes
    /*if ($app['debug']) {
        return;
    }*/

    if ($code == 404) {

        $loader = $app['dataloader'];
        $data = array(
            'global' => $loader->load('global'),
            'common' => $loader->load('common', $app['locale']),
            'header' => $loader->load('header', $app['locale']),
            'footer' => $loader->load('footer', $app['locale'])
        );

        return new Response( $app['twig']->render('404.html.twig', array( 'data' => $data )), 404);
    }

    return new Response('We are sorry, but something went terribly wrong.', $code);

});

When trying to access http://localhost:8888/index_dev.php/my-non-existing-page, I get my 404 template rendered and displayed as expected.

When trying to access http://localhost:8888/my-non-existing-page, my 404 template is not rendered and I get a standard 404 error page instead !

Might be difficult to help me. Feel free to ask for more details if needed. I am simply willing to understand better what is actually happening here.

Answer

gunnx picture gunnx · Aug 16, 2012

You will need to rewrite requests to your index.php file. See below for a basic example to get this working.

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