How to Specify a Vary: Accept-Encoding header in Nginx?

A few days ago I was working optimizing one of our company blogs. I was using a public performance test tool to find out which aspects of the web performance I needed to improve to get better speed.

One of the bottlenecks I found was this warning:

Specify a Vary: Accept-Encoding header

What does this mean?

This means the  web server must be configured to include the “Vary: Accept-Encoding” response header when any common gzip based directives are enabled (for example gunzip, gzip, gzip_static)

What is “Vary: Accept-Encoding”?

Vary: Accept-Encoding is just part of the web header information. Altough it’s present on the gzip configuration block as we’ve seen before, it is more related to caching than gzip compression.

When the “Vary: Accept-Encoding” header is enabled, it reports the client that the file is able to be cached or not. Vary: Accept-Encoding defines the way the server will deal with file caching.

For example: if there is a request to a file that was previously cached, it will be served from the cached files. However, if the Accept-Encoding header is present and the new request is rather different from the previously cached version, it will be managed as a new request, and therefore will be served without any cache.

So, started digging a little bit more on how to specify a vary: accept-encoding header on Nginx, and this is the best way to do it.

How to Specify a Vary: Accept-Encoding header in Nginx ?

Edit Nginx main configuration file:

nano -w /etc/nginx/nginx.conf

Then make sure you have gzip configurations enabled and that you have a line called:

gzip_vary on;

The full gzip configuration should look like this:

gzip on;
gzip_min_length 1100;
gzip_buffers 4 32k;
gzip_types text/plain application/x-javascript text/xml text/css;
gzip_vary on;

Save the file and reload Nginx to apply the changes.

service nginx reload

All done. Now you should know how to Specify a Vary: Accept-Encoding header in Nginx web server.

Btw, if you are looking for a better compression algorithm than mod_gzip or deflate, I recommend you using Brotli, you can read more at this tutorial: Install Brotli Compression on Nginx

Further reading:

 
 

About the Author: Martin Keler

Leave a Reply

Your email address will not be published. Required fields are marked *