Rails应用程序中的尾随斜杠行为 [英] Trailing Slash Behavior in Rails Application

查看:80
本文介绍了Rails应用程序中的尾随斜杠行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在尝试使用类别/文章架构来模仿Rails中的文件夹/文件行为.所以,我在路线上有这个东西:

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'

基本上,请求网址是:

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

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

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 ?

使用Rails 3,nginx,ruby 1.9.2.谢谢!

Using Rails 3, nginx, ruby 1.9.2. Thanks!

推荐答案

我不确定Rails中没有适合您的东西,但这应该可以做到:

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

这篇关于Rails应用程序中的尾随斜杠行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆