【问题标题】:Rails 3 and Strange Accept HeadersRails 3 和奇怪的接受标头
【发布时间】:2011-02-05 04:56:53
【问题描述】:

我的 Rails 3 网站被带有奇怪的接受标头的爬虫攻击,触发异常

ActionView::MissingTemplate occurred in home#show

以下是一些导致问题的接受标头

text/*
application/jxw
*/*;q=0.1

在这些情况下,这被解释为请求的格式,因此会导致缺少模板错误。我真的不在乎我返回给这些爬虫什么,而只是想避免异常。

【问题讨论】:

标签: ruby-on-rails ruby-on-rails-3


【解决方案1】:

您可以在您的应用程序控制器中从这样的异常中解救出来,并改为呈现 HTML 模板:

class ApplicationController
  rescue_from ActionView::MissingTemplate, :with => :render_html

  def render_html
    if not request.format == "html" and Rails.env.production?
      render :format => "html"
    else
      raise ActionView::MissingTemplate
    end
  end
end

【讨论】:

  • 等等什么? not request.format == "html"?您是说 `request.format != "html" 吗?
  • 有没有一种好方法可以在我的本地环境中发出请求来模拟相关问题?我想尝试此修复,但我希望能够在将其部署到生产之前确保它对我们有用。
  • 另外,接受一个异常参数并引发它,例如,def render_html(exception) ... raise exception
  • @blim8183 删除 and Rails.env.production?, curl -H "Accept: */*;" -v http://localhost:3000
【解决方案2】:

因为 SO 在我的声望达到 50 之前阻止添加 cmets,所以我必须提交一个新的答案才能在 cmets 中回复 Ryan Bigg 的问题。

not request.format == "html" 或多或少与request.format != "html" 相同。 andornot 在逻辑上与 &&||! 相同——但是,它们的优先级要低得多。因此,在此示例中,== 运算符在 not 运算符之前进行计算,因此它产生与使用 != 相同的结果。

【讨论】:

  • 当然,但是 Ryan 很可能意味着 not foo == bar 的措辞方式比 foo != bar 更难解析(对于人类)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多