Search code examples
phpherokusilex

Heroku silex route show 404 except "/"


This piece of code was from an example at heroku. But except the route /, anything else I add does not work. It shows 404:

The requested URL /e was not found on this server.

$app->match('/', function(Symfony\Component\HttpFoundation\Request $request) use ($app) {
    return $app['twig']->render('index.twig');
});

$app->match("/dump", function(Symfony\Component\HttpFoundation\Request $request) use ($app) {
    return new Response('Thank you for your feedback!', 201);
})->bind("dump");
$app->get("/t", function() use ($app) {
    return new Response('Thank you for your feedback!', 201);
})->bind("t");
$app->get("/d", function() {
    return new Response('Thank you for your feedback!', 201);
})->bind("d");
$app->get("/e", function() {
    return new Response('Thank you for your feedback!', 201);
});
$app->run();

Edit 1 I deployed it directly on heroku server (heroku auto build on each push to master branch)

Edit 2 my workspace:

bin\worker.php
www\index.php <== the snippet is from this file
www\list.php
apache_app.conf
app.php  <== basic init, return Silex\Application $app
Procfile

The content of apache_app.conf is copied from this link. RewriteEngine On

RewriteCond %{REQUEST_URI}::$1 ^(/.+)/(.*)::\2$
RewriteRule ^(.*) - [E=BASE:%1]

RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteRule ^app\.php(/(.*)|$) %{ENV:BASE}/$2 [R=301,L]

RewriteCond %{REQUEST_FILENAME} -f
RewriteRule .? - [L]

RewriteRule .? %{ENV:BASE}/app.php [L]

I figured that I need to change the apache config somehow, but I don't understand htaccess syntax.


Solution

  • For apache2, you can add a .htaccess file within "/web"

    <IfModule mod_rewrite.c>
        Options -MultiViews
    
        RewriteEngine On
        #RewriteBase /path/to/app
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteRule ^ index.php [QSA,L]
    </IfModule>
    

    and set your Procfile as:

    web: vendor/bin/heroku-php-apache2 web/
    

    For nginx, create a nginx conf file with content:

    location / {
        # try to serve file directly, fallback to rewrite
        try_files $uri @rewriteapp;
    }
    
    location @rewriteapp {
        # rewrite all to index.php
        rewrite ^(.*)$ /index.php/$1 last;
    }
    
    location ~ ^/(index|index_dev)\.php(/|$) {
        try_files @heroku-fcgi @heroku-fcgi;
        internal;
    }
    

    and set Procfile as:

    web: vendor/bin/heroku-php-nginx -C server_conf/nginx.conf web/