Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 227
dreeves Avatar asked Feb 25 '23 09:02

dreeves


1 Answers

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 )

like image 101
dreeves Avatar answered Feb 26 '23 22:02

dreeves