Actually, that seems to be a known problem between users of the Symfony
.
I use a framework called Laravel that seems to know this bar problem well at the end of the url.
Using the HTACCESS
The correction for this can be made in the configuration of .htaccess
where, if the accessed url has a bar /
at the end, it is redirected to url without the bar at the end.
Behold:
# Remove a barra do final se não for uma pasta
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [L,R=301]
I believe that this should be enough for its application to work properly.
There is one small detail that should be noted regarding this: When you submit a request of type POST
, the redirection will not take with it the data sent, since the redirection takes place in GET
.
Modifying REQUEST_URI
For those who don’t know, Silex requests use the library internally Symfony Http Foundation
. By the method Request::createFromGlobals()
all request data is captured via superglobal variables ($_GET
, $_POST
, $_SERVER
, etc....).
You can easily fix this problem by placing before the stretch where you call $app->run()
the following code:
$_SERVER['REQUEST_URI'] = preg_replace('|/$|', '', $_SERVER['REQUEST_URI'], 1);
Manipulating the property server
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 by making a small change in the call to $app->run()
.
You will need to instantiate Request
, make a small modification and pass it as instance of $app->run()
.
Behold:
$request = Request::createFromGlobals();
$request->server->set('REQUEST_URI', rtrim($request->server->get('REQUEST_URI'), "/"));
$app->run($request);
I preferred this last form since you do not change the value of the super global variable $_SERVER
.
References:
Your problem is also described in Stackoverflow, in How to make route "/" ending optional
A route defined with a
/
at the end will also match a URL without the/
at the end when there is no route for it. Either you have both routes or use only one with the/
in the end and you should have your problem solved.– Zuul
I would only like a solution to access /home and /home/ without having to create two routes for each URL
– adrianosymphony
If you have
$app->get('/home/', function(){
should give you the same result for both Urls:http://www.example.com/home/
andhttp://www.example.com/home
.– Zuul
Unfortunately to my surprise this is not how it happened unless you know some procedure you have not followed.
– adrianosymphony