如何在Rails路由中使用正则表达式进行重定向? [英] How do I use regular expressions in a Rails route to make a redirection?

查看:63
本文介绍了如何在Rails路由中使用正则表达式进行重定向?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的route.rb中尝试重写的规则可能是不言自明的:

This attempted rewrite rule in my routes.rb is probably self-explanatory:

match "/:user/:photo-thumb.png" => 
      redirect("/%{user}/photos/%{photo}/image?style=thumb"),
      :photo => /[a-zA-Z]+/

我想重定向诸如mysite.com/alice之类的内容/foo-thumb.png到mysite.com/alice/photos/foo/image?style=thumb

I want to redirect something like mysite.com/alice/foo-thumb.png to mysite.com/alice/photos/foo/image?style=thumb

上述尝试不过是错误的。有任何解决方案吗?

The above attempt is wrong though. Any ideas for fixing it?

推荐答案

以下方法对我有用:

match "/:user/:photo_thumb.png" => 
      redirect{|p| 
        "/#{p[:user]}/photos/#{p[:photo_thumb].split('-')[0]}/image?style=thumb"
      },
      :constraints => { :photo_thumb => /[a-zA-Z]*\-thumb/ }

我很想找到一种更简单的方法。 (正如塔德曼指出的那样,我最好通过nginx重写来做到这一点。请参阅以下相关问题: Routes.rb,机架重写,nginx / apache重写规则

I'd love to find a simpler way to do it though. (As tadman points out, I may be better off doing this with nginx rewrites. See this related question: Routes.rb vs rack-rewrite vs nginx/apache rewrite rules )

这篇关于如何在Rails路由中使用正则表达式进行重定向?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆