Minify and Gzip

Cédric Jeanneret nginx at
Tue Aug 9 14:02:47 UTC 2011


I just wanted to share a perl script I made for nginx. Its aim is to:
- minify CSS (and by a simple modification JS)
- deflate it
- keep it as a local file

It's based on the nice 
with the use of IO::Compress::Gzip.

Any comment/improvement is welcome.



== Script ==

package CSSMinify;
use nginx;
use CSS::Minifier qw(minify);
use IO::Compress::Gzip ;

sub handler {
   my $r=shift;
   my $cache_dir="/tmp"; # Cache directory where minified file will be 
   my $cache_file=$r->uri;
   $cache_file=join("/", $cache_dir, $cache_file);
   my $uri=$r->uri;
   my $filename=$r->filename;
   return DECLINED unless -f $filename;

   $r->header_out('Cache-Control', '30d, must-revalidate');
   return OK if $r->header_only;
   if (! -f $cache_file) {
     open(INFILE, $filename) or die "Error reading file: $!";
     my $output = minify(input => *INFILE);
     my $gz = new IO::Compress::Gzip($cache_file, Minimal => 1, 
AutoClose => 1, Append => 0) or return 0;
     print $gz $output;

   return OK;

More information about the nginx mailing list