在我的rails答案中删除不必要的HTTP标头

ibl*_*lue 6 ruby-on-rails http

我目前正在开发一个大小很重要的API:我希望答案包含尽可能少的字节.我优化了我的JSON答案,但rails仍然响应了很多奇怪的标题

HTTP/1.1 200 OK
Server: nginx/0.7.67                            # Not from Rails, so ok.
Date: Wed, 25 Apr 2012 20:17:21 GMT             # Date does not matter. We use ETag Can I remove this?
ETag: "678ff0c6074b9456832a710a3cab8e22"        # Needed.
Content-Type: application/json; charset=utf-8   # Also needed.
Transfer-Encoding: chunked                      # The alternative would be Content-Length, so ok.
Connection: keep-alive                          # Good, less TCP overhead.
Status: 200 OK                                  # Redundant! How can I remove this?
X-UA-Compatible: IE=Edge,chrome=1               # Completely unneded.
Cache-Control: no-cache                         # Not needed.
X-Request-Id: c468ce87bb6969541c74f6ea761bce27  # Not a real header at all.
X-Runtime: 0.001376                             # Same goes for this
X-Rack-Cache: invalidate, pass                  # And this.
Run Code Online (Sandbox Code Playgroud)

所以有很多不必要的HTTP标头.我可以在我的服务器(nginx)中过滤它们,但有没有办法直接在rails中停止它?

x1a*_*1a4 10

您可以使用一个Rack中间件来完成此操作.有关在一个中执行此操作的示例,请参阅https://gist.github.com/02c1cc8ce504033d61bf.

将其添加到您的应用配置时,请使用类似的功能 config.middleware.insert_before(ActionDispatch::Static, ::HeaderDelete)

您希望在运行时显示的列表中的第一项之前插入它rake middleware,在我的情况下是这样ActionDispatch::Static.

http://guides.rubyonrails.org/rails_on_rack.html如果你以前没有在Rails上下文中暴露过Rack,可能会有所帮助.


Ste*_*thy 9

另外一个选项,因为你正在使用Nginx,是HttpHeadersMoreModule.这将允许您精确控制精确控制哪些标头沿线传输.

在您的情况下,您特别希望使用more_clear_headers指令,如下所示:

more_clear_headers Server Date Status X-UA-Compatible Cache-Control X-Request-Id X-Runtime X-Rack-Cache;

这也清除了Server标题,因为它并不是必需的,如果你试图保存字节,每一点都有帮助.

这个模块确实需要你自己编译Nginx,但这真的不应该吓到你.Nginx非常容易编译,只需按照安装说明操作即可.