Why is the path not recognized by Silex when there is a slash "/" at the end of the requested url?

8

I'm starting my MVC studies with silex today, but I'm having trouble creating routes by accessing addresses containing a slash at the end. Example:

http://site.com.br/home/

I have already been able to access the url only in the http://site.com.br/home path.

Is there any way to access the same content by accessing the two urls? Here is the code I'm using:

require_once "vendor/autoload.php";

$app = new Silex\Application();
$app['debug'] = true;

$app->get('/home', function(){
    return  "Você acessou a sua HOME";
});

$app->run();
    
asked by anonymous 31.10.2014 / 20:23

2 answers

4

In fact, this seems to be a known problem a> among users of the Symfony route library.

I use a framework called Laravel that seems to know this bar problem at the end of the url.

Using HTACCESS

The correction for this can be made in the configuration of .htaccess where, if the url accessed has a / bar at the end, it is redirected to url without the slash at the end.

See:

# Remove a barra do final se não for uma pasta
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [L,R=301]

I think this should already be enough for your application to work properly.

There is a small detail to note: When you send a request of type POST , the redirection will not take the data sent with you, since redirection happens in GET .

Modifying REQUEST_URI

For those who do not know, Silex requests internally use the Symfony Http Foundation library. By means of the Request::createFromGlobals() method all request data is captured through the superglobals variables ( $_GET , $_POST , $_SERVER , etc ...).

You can easily fix this problem by placing before the excerpt where you call $app->run() the following code:

$_SERVER['REQUEST_URI'] = preg_replace('|/$|', '', $_SERVER['REQUEST_URI'], 1);

Manipulating property server of class Symfony\Component\HttpFoundation\Request

After running some tests with Silex, I came to the conclusion that the most organized way to solve the problem is to make a small change in the $app->run() call.

You will need to instantiate Request , make a small modification, and pass it as an instance of $app->run() .

See:

$request = Request::createFromGlobals();

$request->server->set('REQUEST_URI', rtrim($request->server->get('REQUEST_URI'), "/"));

$app->run($request);

I preferred this last one since you do not change the value of the global super variable $_SERVER .

References :

Your problem is also described in Stackoverflow in English, How to make route "/" ending optional

    
14.04.2017 / 16:08
1

This is an expected behavior of the Symfony route component link .

However, there is a page in their documentation that explains how to create a redirect control:

link

Remember to put this route as the last route to run (if there is no risk of error).

    
26.03.2015 / 19:50