Francisc
Francisc

Reputation: 80495

Allow optional trailing slash when using optional parameter

Given this path: /page(/:pageID), how can I allow the following variations:

Thank you.

Upvotes: 5

Views: 3578

Answers (5)

Zoltán Hajdú
Zoltán Hajdú

Reputation: 535

An example for Slim V3:

/[{param1:[0-9]+}[/[{param2:[0-9]+}[/]]]]

This will cover:

/
/1
/1/
/1/2
/1/2/

Upvotes: 1

seus
seus

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

Igor
Igor

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

Fabien Snauwaert
Fabien Snauwaert

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

nilfalse
nilfalse

Reputation: 2419

You must define your route this way:

$app->get('/page(/:id/?)', function ($id = NULL) use ($app) {
    ; // your code
});

Upvotes: 8

Related Questions