Ruby-on-rails – How to redirect using regular expressions in Rails routes?

My attempt to rewrite the rules in routes.rb might be self-explanatory:

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

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

But the above attempt was wrong. Any ideas to fix it?

The following works for me:

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

I would love to find an easier way to do this. (As tadman pointed out, it might be better to rewrite with nginx. Please refer to this related question: Routes.rb vs rack- rewrite vs nginx/apache rewrite rules)

My attempt to rewrite rules in routes.rb may be self-explanatory:

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

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

But the above attempt is wrong. Any ideas to fix it?

The following works 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 would like to find one Easier way to do this. (As tadman pointed out, rewriting with nginx might be better. Please refer to this related question: Routes.rb vs rack-rewrite vs nginx/apache rewrite rules)

Leave a Comment

Your email address will not be published.