2

I have a server serving up a JS file a few million times a day using apache2. Some of my users would like the JS to be gzipped. Does anyone know how apache2 mod_deflate handles compression of static files? Will it compress the js for each request(in which case I'd be worried about cpu load)? If it does, is there a way to pre-compress the JS files so apache2 wouldn't have to do this for each file?

  • 2
    See this post on Stack Overflow: http://stackoverflow.com/questions/75482/how-can-i-pre-compress-files-with-mod-deflate-in-apache-2-x – Phil Ross Apr 11 '10 at 22:20
  • mod_deflate will keep compressed files in memory the best it can. Obviously memory constraints play into which files will be cached and for how long. If you want to ensure certain files are cached all the time see the Multiviews instructions below. – Chris S Jan 23 '12 at 21:44

1 Answers1

1

You can do it with

Options +Multiviews

then precompress the file as whatever.js.gz using

gzip -c -9 whatever.js > whatever.js.gz

However, if there are older browsers that may break with this.

In the apache config

AddEncoding x-gzip .gz

Remove

AddType application/x-gzip .gz
  • 1
    At least in current versions of Apache (2.4.25 at the moment) the Multiviews only kicks in if the originally named file does *not* exist. So you'd always serve `whatever.js` even if the compressed version exists. – MvG Jan 20 '17 at 20:11
  • @MvG, thanks, you saved me a lot of time. Now I have to figure out a workaround (could just move the uncompressed files). The requested file, some.xml, doesn't exist, but both some.xml.en and some.xml.en.gz exist. Apache 2.2 gave preference to the compressed version, but 2.4 isn't. I'm checking configuration to see if I've missed something. – jimhark Apr 20 '18 at 15:14
  • Switched from Apache 2.2's some.xml.en / some.xml.en.gz to some.xml.xml / some.xml.gz for Apache 2.4 and it's now working. Multiviews will serve some.xml.xml when some.xml is requested and compression is not supported on the client (request doesn't have ;Accept-Encoding: gzip') header. If compression is supported, some.xml.gz will be served (as a static compressed file). – jimhark Apr 21 '18 at 03:25
  • 1
    Good information can be found at https://kevinlocke.name/bits/2016/01/20/serving-pre-compressed-files-with-apache-multiviews/#non-negotiated-files and https://feeding.cloud.geek.nz/posts/serving-pre-compressed-files-using/, but I had to adapt th esuggested config for my needs. – jimhark Apr 21 '18 at 03:27
  • fyi: Does not work on apache 2.4 It will send the file with the right name but gzip content. – John Jan 06 '21 at 02:01