Reputation: 80495
Given this path: /page(/:pageID)
, how can I allow the following variations:
/page
and /page/
(even if the pageID part is missing./page/1
and /page/1/
Thank you.
Upvotes: 5
Views: 3578
Reputation: 535
An example for Slim V3:
/[{param1:[0-9]+}[/[{param2:[0-9]+}[/]]]]
This will cover:
/
/1
/1/
/1/2
/1/2/
Upvotes: 1
Reputation: 671
As stated in the documentation, optional segments may be unstable depending on the usage. For example, with the answer given by Fabien Snauwaert, and the following routes:
/:controller(/)(:action(/)(:overflow+/?)) /:controller(/)(:action(/:overflow+/?))
If not filled all the arguments, when obtain param values, these will be in a position to the right, resulting in action == controller
and overflow == action
.
To prevent this, a simple solution is to put the optional slash at the end of the route.
/:controller(/:action(/:overflow+))/? /:controller(/:action(/:overflow+))(/)
And it is more readable, isn't it?
I can not comment on others answers, so I write here a detail concerning the Igor response.
One "problem" with this approach is that if the user tries to access a page that does not exist, and also do with a trailing slash, will be a 301 redirect to display a 404 page. Maybe a little weird.
Upvotes: 2
Reputation: 2659
I found this way to achive this with Apache mod_rewrite enabled. Snippet of .htaccess
RewriteEngine On
# remove trailing slash
RewriteCond %{HTTPS} off
RewriteRule ^(.+[^/])/$ http://%{HTTP_HOST}/$1 [R=301,L]
RewriteCond %{HTTPS} on
RewriteRule ^(.+[^/])/$ https://%{HTTP_HOST}/$1 [R=301,L]
Upvotes: 1
Reputation: 5651
The answer provided by @inst would not work here (Slim 2.0.0 running on XAMPP): /page/ gives out a 404.
This works in all four cases though:
$app->get('/page(/)(:id/?)', function ($id = NULL) use ($app) {
echo 'success';
});
Upvotes: 4
Reputation: 2419
You must define your route this way:
$app->get('/page(/:id/?)', function ($id = NULL) use ($app) {
; // your code
});
Upvotes: 8