Would mod_deflate or equivalent (mod_gzip in older Apache versions, static and dynamic compression can be enabled easily in recent versions of IIS too) not do this for you?
If you are worried about the CPU cost of the compression and added request latency, you can pre-compress static content with most modern web servers (see http://stackoverflow.com/questions/75482/how-can-i-pre-compr... for Apache info).