Trailing Slash Behavior in Rails Application

不羁的心 提交于 2019-12-11 07:44:11

问题


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:


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


来源:https://stackoverflow.com/questions/6186780/trailing-slash-behavior-in-rails-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!