Accept-Encoding headers on Cloudfront serving asse

2019-06-28 03:47发布

问题:

When I use my Rails app to directly serve my assets through Heroku's Cedar stack (ie. NOT through a CDN) they get gzip'd automatically. (See my previous question on why I'm confused about this)

Now, I'm trying to set up Cloudfront to serve these assets instead, and ideally, I'd like for them to be gzip'd as well. From what I've read, I thought that Cloudfront would pass on the Accept headers to my app, so they should be served up gzip'd if supported (just as they are when you make a direct request to the asset on heroku). But this isn't the case. The asset headers end up looking like this:

Age:510
Connection:keep-alive
Content-Length:178045
Content-Type:text/css
Date:Sun, 08 Jan 2012 18:55:13 GMT
Last-Modified:Sun, 08 Jan 2012 18:42:34 GMT
Server:nginx/0.7.67
Via:1.1 varnish, 1.0 7a0b4b3db0cc0d369fe1d6981bfb646a.cloudfront.net:11180 (CloudFront), 1.0 6af08f4042ec142b4b760ca4cd62041d.cloudfront.net:11180 (CloudFront)
X-Amz-Cf-Id:2b205edf4e9ef000a31a0208ca68f4e15b746eb430cde2ba5cc4b7dff4ba41a76c24f43cf498be02,8d5863a42eea452f86831a02f3eb648b26fe07013b08b95950f15ef8ba275822e1eb3b7ed2550d01
X-Cache:Hit from cloudfront
X-Varnish:2130919357

There's no mention of encoding here, and when I view the plain file, it's not gzip'd. So I'm wondering what I need to do here to get Cloudfront to request a gzip'd version of the asset from my app so that it can serve this to the client.

This post says you need to manually gzip and upload the file, but I don't see why that should be necessary. For one, it's annoying, and two, wouldn't it request the file the same as my browser directly? So why wouldn't it just serve up the gzip'd file as it does by default in my app?

Any tips on getting gzip'ng working properly would be great. I'd like to not have to manually gzip my files and upload them if possible.

回答1:

Cedar served files do NOT get GZipped by the stack, Cedar only serves whatever you have in the application code. See the documentation:

Since requests to Cedar apps are made directly to the application server – not proxied through an HTTP server like nginx – any compression of responses must be done within your application. For Rack apps, this can be accomplished with the Rack::Deflater middleware. For gzipped static assets, make sure that Rack::Deflater is loaded before ActionDispatch::Static in your middleware stack.

Therefore the GZipping your seeing either is a false header, or is coming from somewhere else which. Therefore if you've just pushed files to Cloudfront then you're just seeing the same thing.

If you're looking at serving zipped assets via CDN I would really recommend looking at bumping to Rails 3.1 and using the Asset pipeline. Not only will this give you more control over your assets bu also give you a much easier path to serving them over a CDN.