Forum Moderators: phranque

Message Too Old, No Replies

Pre-Compress files with gzip?

         

elliotgoodrich

6:04 pm on Jul 6, 2007 (gmt 0)

10+ Year Member



I know how to get apache to compress files on-the-fly. However I'm not sure how to compress files beforehand (manually with gzip etc), then get apache to serve them instead.

Since I have files that I rarely change, I want all the benefits of a small file size, with none of the CPU strain.

Thanks.

jdMorgan

7:10 pm on Jul 6, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Let's say you have a file foo.html, and also a compressed version, foo.html.gz, snd you're willing to take care of keeping the compressed files updated manually.

In that case, a simple bit of mod_rewrite code can be used:


# If client accepts compressed files
RewriteCond %{HTTP:Accept-Encoding} gzip
# and if compressed file exists
RewriteCond %{REQUEST_FILENAME}.gz -f
# send .html.gz instead of .html
RewriteRule ^(.+\.html)$ /$1.gz [L]

If more functionality is needed, for example, to compress files if compressed versions don't exist, or to make sure that the compressed file is newer than the uncompressed file, then you'll need a script. PERL would seem to be the best choice for this job. You can have the script check for a compressed version, send it if available and if newer than the original source, or create a new compressed file if needed. In that case, you'd only need a somewhat-simpler mod_rewrite rule:

# If client accepts compressed files
RewriteCond %{HTTP:Accept-Encoding} gzip
# rewrite html requests to the compressed-file handler script
RewriteRule ^(.+\.html)$ /compressor.pl?file=$1 [L]

In some cases, you might want the script to go ahead and send the uncompressed file to the client if no current compressed version exists, and then create a new compressed file. This would prevent the client from having to wait while the requested file was compressed. It's a trade-off between server bandwidth and perceived site performance.

Just some ideas...

Jim

elliotgoodrich

7:58 pm on Jul 6, 2007 (gmt 0)

10+ Year Member



The first section of code is perfect thankyou.

# If client accepts compressed files
RewriteCond %{HTTP:Accept-Encoding} gzip
# and if compressed file exists
RewriteCond %{REQUEST_FILENAME}.gz -f
# send .html.gz instead of .html
RewriteRule ^(.+)\.(css¦html)$ /$1.$2.gz [L]

I've modified it so it will do CSS aswell.

The website is hand done in HTML (like the old days), and I don't mind manually creating the gzipped versions.

jdMorgan

8:50 pm on Jul 6, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



You could also nest these: :)

RewriteRule ^(.+\.(css¦html))$ /$1.gz [L]

Jim