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

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

问题描述

在我的 routes.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/ }

不过,我很想找到一种更简单的方法.(正如 tadman 指出的那样,我最好用 nginx 重写来做这件事.看到这个相关的问题:Routes.rb vs rack-rewrite vs 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天全站免登陆