How do I use regular expressions in a Rails route

2019-02-18 22:13发布

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?

2条回答
我命由我不由天
2楼-- · 2019-02-18 22:26

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.

查看更多
等我变得足够好
3楼-- · 2019-02-18 22:36

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 )

查看更多
登录 后发表回答