简体   繁体   English

使用可选参数时允许可选的尾部斜杠

[英]Allow optional trailing slash when using optional parameter

Given this path: /page(/:pageID) , how can I allow the following variations:鉴于此路径: /page(/:pageID) ,我如何允许以下变化:

  • /page and /page/ (even if the pageID part is missing. /page/page/ (即使缺少 pageID 部分。
  • /page/1 and /page/1/ /page/1/page/1/

Thank you.谢谢你。

You must define your route this way:您必须以这种方式定义您的路线:

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

The answer provided by @inst would not work here (Slim 2.0.0 running on XAMPP): /page/ gives out a 404. @inst 提供的答案在这里不起作用(在 XAMPP 上运行的 Slim 2.0.0):/page/ 给出 404。

This works in all four cases though:这适用于所有四种情况:

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

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:例如,使用 Fabien Snauwaert 给出的答案,以及以下路线:

/: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 .如果没有填满所有的参数,当获取 param 值时,这些将在右边的位置,导致action == controlleroverflow == 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.我无法评论其他人的答案,所以我在此写下有关 Igor 回复的详细信息。

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.这种方法的一个“问题”是,如果用户尝试访问一个不存在的页面,并且还使用尾部斜杠,那么 301 重定向将显示 404 页面。 Maybe a little weird.也许有点奇怪。

I found this way to achive this with Apache mod_rewrite enabled.我发现这种方法可以在启用 Apache mod_rewrite 的情况下实现。 Snippet of .htaccess .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]

An example for Slim V3: Slim V3 的示例:

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

This will cover:这将涵盖:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM