这些错误来自于GoogleBot 格式化其HTTP_ACCEPT
header。有效期间(参见 W3 参考 http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html),它添加了一个q=0.6
(最后一个数字可能会改变)用作分隔符。由于没有指定其他媒体类型,因此q=0.6
没有必要,我认为这就是 Rails 没有正确处理 header 的原因。
(这似乎取决于 Rails 版本。在 Rails 3.0.12 上,它引发了MissingTemplate
例外。)
将先前答案中的以下代码添加到相关控制器是不够的:它会返回错误406
.
respond_to do |format|
format.html
end
为了使其在 Rails 3.0.12 下工作并且将某些内容返回给 GoogleBot(比406
错误),您需要添加此代码,将请求的格式设置为html
一旦*/*;q=0.6
-like HTTP_ACCEPT
检测到(Rails 将标头值加载到request.format
).
# If the request 'HTTP_ACCEPT' header indicates a '*/*;q=0.6' format,
# we set the format to :html.
# This is necessary for GoogleBot which perform its requests with '*/*;q=0.6'
# or similar HTTP_ACCEPT headers.
if request.format.to_s =~ %r%\*\/\*%
request.format = :html
end
respond_to do |format|
format.html
end
在工作时,该解决方案需要将代码添加到您想要由 GoogleBot 索引的任何控制器操作中,这真的不是 DRY!
为了彻底解决这个问题,我实现了一个小型 Rack 中间件,它的效果甚至更好:它检查请求的HTTP_ACCEPT
标头,并将替换任何匹配的标头*/*;q=0.6
(数字可能有所不同)由共同的*/*
。这甚至更好,因为自从q=0.6
如果后面没有其他媒体类型,则没有任何意义,标头的更改不会改变其含义。我们不会强迫 Rails 成为任何给定的格式,我们只是以它可以理解的方式告诉它任何将要做的事情。
您可以在此找到中间件、加载初始化程序和集成测试gist https://gist.github.com/2590040/93cb2faca1ba5ead73222e74ca11790e3efb22de.
宝石版本在这里:https://github.com/ouvrages/rails_fix_google_bot_accept https://github.com/ouvrages/rails_fix_google_bot_accept