开发者

How do I use regular expressions in a Rails route to make a redirection?

开发者 https://www.devze.com 2023-03-01 02:49 出处:网络
This attempted rewrite rule in my routes.rb is probably self-explanatory: match \"/:user/:photo-thumb.png开发者_运维百科\" =>

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]+/

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?


The following worked for me:

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/ }

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 )


You may have more luck with something like this:

match "/:user/:photo.png" => 
  redirect("/%{user}/photos/%{photo}/image?style=thumb"),
  :photo => /\w+\-thumb/

The route tokens can be confused by having additional content in them.

As a note, this sort of thing is often better handled on the web server level, like Apache, nginx or lighttpd, where redirects won't tie up instances of your Rails stack. Having a large mapping table is not uncommon in applications with significant numbers of legacy links.

0

精彩评论

暂无评论...
验证码 换一张
取 消