【问题标题】:Redirect with wildcard-matching使用通配符匹配重定向
【发布时间】:2017-05-01 14:01:29
【问题描述】:

我正在将我的应用程序中的 /widgets 路由重命名为 /thingers,并且我希望能够通过一行将所有与 widget 相关的 URL 重定向到它们的 thinger 对应的 URL。

类似:

get '/widgets(*anything)', to: redirect('/thinger%{anything}'), 
    as: 'widgets_redirect'

^^^这不起作用:它将斜杠传递为%2F30%2F,并且根本不传递文件扩展名。

我唯一可行的解​​决方案是几行:

get '/widgets', to: redirect('/thingers'), as 'widgets_redirect'
get '/widgets/:id', to: redirect('/thingers/%{id}')
get '/widgets/:id/:action.:ext', to: redirect('/thingers/%{id}/%{action}.%{ext}')
get '/widgets/:id/:action', to: redirect('/thingers/%{id}/%{action}')

*edit:交换最后两行,否则没有文件扩展名的那一行会匹配并错误地处理带有扩展名的请求。

如何用一行代码涵盖所有这些情况?

【问题讨论】:

    标签: ruby-on-rails redirect routing


    【解决方案1】:

    .字符在 ActionController::Routing::SEPARATORS 中定义,它列出了用于拆分 URL 的特殊字符。这就是为什么你所有的扩展都被切断了。

    如果你想避免在 .s 处拆分 URL,你需要传递一个 :constraints => { :yourvalue => /regexp/ } 参数

    您也可以尝试使用扩展名重定向所有链接:

    这两条路线将为您提供您想要实现的目标:

    get '/widget', to: redirect('/thingers')
    get 'widget/:thingy', to: redirect('/thingers/%{thingy}'), :constraints => { :thingy => /.*/ }
    

    【讨论】:

    • 为什么/.*/ 不包括斜线?
    • 确实如此。您现在为 ex 编写的任何链接:/widget/something/another.txt 将被重定向到 /thingers/something/another.txt
    • 不幸的是它没有:斜​​杠仍然是 URL 编码而不是通过,所以对于 /widgets/info.json,我被重定向到 /thingers30%2Finfo.json。我还想知道如果可以匹配斜杠,为什么您的解决方案需要两行 - 为什么不只是 redirect('/thingers%{thingy}')
    猜你喜欢
    • 2015-08-03
    • 1970-01-01
    • 2013-03-12
    • 2015-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-03
    • 2016-09-07
    相关资源
    最近更新 更多