1

我目前正在尝试使用类别/文章模式来模仿 rails 中的文件夹/文件行为。所以,我在路线上有这个:

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

基本上,请求网址是:

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

一切正常。问题是它运作良好。http://www.example.com/category像(不带斜杠)这样的 url也提供文章列表。它是否存在一种方法来阻止它使用 404 或更好地重定向到带有斜杠的类别?

使用 Rails 3、nginx、ruby 1.9.2。谢谢!

4

1 回答 1

2

我不确定rails中没有什么东西可以为你做这件事,但这应该可以:

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
于 2011-05-31T12:57:28.617 回答