Compressing static files on web server

Now that the average web page size approaches 1MB and people more often use all the possible JS frameworks (such as jQuery, Prototype, etc.) while needing just 0.000001% of the whole solution, and especially not minifying or compressing the files, the web page loading speeds become essential even though you may have all the necessary bandwidth in the world. With all this, people have started using dynamic file-compressing methods that will compress/decompress the files on-the-fly. However, very often the largest files are static like Javascript frameworks mentioned before, therefore compressing them every time on server-side is waste of resources, especially if it is a high-traffic site. Therefore the simple solution is:

1. Compressing the file beforehand (then renaming it back to original file extension like file.js, not file.js.gz)

2. Configuring particular files to be treated as compressed ones (so that they get decompressed when downloaded in web-browser)

For that, here are configuration examples for compressing particular files to gzip in particular folders on Apache and nginx web servers.


<Directory “/var/www/static”>
  <Files static.js>
    ForceType text/javascript
    Header set Content-Encoding gzip


server {
  location /var/www/static/static.js
    add_header Content-Type ‘text/javascript’;
    add_header Content-Encoding ‘gzip’;

You can compress particular file types by using wildcards before extension like /var/www/static/*.js or compress all the files in folder by specifying just folder, not particular file.

Leave a Reply