HTTP-Compression in rails not working for JSON-responses
Asked Answered
I

1

0

I have rails 3.2.1 application and nginx.

In nginx configurations I set gzip on;, and compressing works for pages, css, js files.

But it does not work for JSON responses. As I found the solution for rails is to add: config.middleware.use Rack::Deflater into application.rb.

And it helps: before response was 45Kb, now near 8Kb.

But, now I found that compression works only in Mac Chrome, Mac Firefox and Windows Chrome.

For IE 10, IE 11 and Windows Firefox - it does not work:

  • I see Accept-Encoding: gzip, deflate in request-header,
  • I don't see Content-Encoding: gzip in response-header,
  • response size is still 45Kb.

Please, help.

Impenetrable answered 19/5, 2015 at 11:11 Comment(6)
probably you just need to modify gzip_types to include application/jsonCzernowitz
@AlexeyTen But why it works only on Mac and Chrome?)))Impenetrable
@AlexeyTen do I need to config.middleware.use Rack::Deflater in application.rb after adding application/json to gzip/types?Impenetrable
I think, you don', cause nginx will do gzippingCzernowitz
You can compress response on backend then Nginx will not try to gzip it again if you have proxy_set_header Accept-Encoding "gzip"; but of course Nginx provide a way better compression configuration. So Alexey Ten right, don't compress on Ruby side, let Nginx handle thatRelucent
@mikhailov many thanks, additionally - don't hesitate to edit my my answer if you see something wrong.Impenetrable
I
2

Fixed by moving compressing configurations from rails to nginx configs. I added to <my_site>.conf:


      # Enable Gzip
      gzip  on;
      gzip_http_version 1.0;
      gzip_comp_level 2;
      gzip_min_length 1100;
      gzip_buffers     4 8k;
      gzip_proxied any;
      gzip_types
        # text/html is always compressed by HttpGzipModule
        text/css
        text/javascript
        text/xml
        text/plain
        text/x-component
        application/javascript
        application/json
        application/xml
        application/rss+xml
        font/truetype
        font/opentype
        application/vnd.ms-fontobject
        image/svg+xml;

      gzip_static on;

      gzip_proxied        expired no-cache no-store private auth;
      gzip_disable        "MSIE [1-6]\.";
      gzip_vary           on;

Thanks @Alexey Ten for help.

It works, but compressing are not visible in IE. Some security programs on Windows catch "gzipped" HTTP-responses, extract it from archive, check for viruses and also remove Content-Encoding: gzip from header of response. IE as usual excelled :)

Impenetrable answered 19/5, 2015 at 11:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.