How to add 304 Not Modified Header to your static assets on Nginx

If you are a web developer, there is one thing to which you should pay attention: Static assets on your hosts should be cached by the browsers if it does not change very often. More specifically, when you request the assets (CSS + JS) for the first time, the files will be downloaded to your browser and cached as local files, and any subsequent requests should reuse those files. This would make your web app become faster and save your server bandwidth. Imagine that your web app is pretty big with lots of JS + CSS, a 2MB JS file would take about 3 seconds to download. That is a big number and usually we don't want users to wait that long whenever they click any links on our website. One simple technique to improve this is to let the browser cache these files.

When the browser detects that the resource has not been changed since the last time it downloads the file, it would return 304 Not Modified status and the cached local files will be used. If you are using Nginx, this could be set easily by setting correct headers for those static files. I am using the following config for my Rails application and it works pretty well. You can just copy and place this in your virtual host configuration file.

location ~ ^/(assets|images|javascripts|stylesheets|system)/ {
        root /var/www/myapp/public;
        gzip_static on;
        expires 1y;
        add_header Cache-Control public;
        add_header ETag "";
}

In order to check if your setting is correct, you can try refreshing the web page after it has been loaded, and you should see the status 304 Not Modified.