开发者

Trailing Slash Behavior in Rails Application

I am currently trying to mimic folder/files behavior in rails with category/articles schema. So, I have this in routes :

 match '/:category/' => 'category#list_articles'
 match '/:category/:article.:format' => 'article#show'

Basically, request urls are :

http://www.example.com/category/
http://www.example.com/category/article.html

Everything works. The problem is it's working to well. An url like http://www.example.com/category (without the trailing slash) serves also the list of articles. Does it exist an a way either to block this with a 404 or better to redirect to the category with the trailing slash ?

Using Rails 3, nginx, ruby 1.9.开发者_JAVA技巧2. Thanks!


I'm not sure there isn't something in rails that does it for you, but this should do:

class TrailingSlashes                                                                                                      
  def initialize(app)
    @app = app
  end

  def call(env)
    if match = env['REQUEST_PATH'].match(/(.*)\/$/)
      response = Rack::Response.new
      response.redirect(match[1])
      response
    else
      @app.call(env)
    end
  end
end
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜