Trailing Slash Behavior in Rails Application

2019-08-13 00:26发布

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.2. Thanks!

1条回答
劳资没心,怎么记你
2楼-- · 2019-08-13 01:02

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
查看更多
登录 后发表回答