Minify and Gzip

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


Hello,

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 http://wiki.nginx.org/NginxEmbeddedPerlMinifyJS 
with the use of IO::Compress::Gzip.

Any comment/improvement is welcome.

Cheers,

C.


== 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 
kept
   my $cache_file=$r->uri;
   $cache_file=~s!/!_!g;
   $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');
   $r->header_out('Content-Encoding'=>'gzip');
   $r->send_http_header;
   return OK if $r->header_only;
   if (! -f $cache_file) {
     open(INFILE, $filename) or die "Error reading file: $!";
     my $output = minify(input => *INFILE);
     close(INFILE);
     my $gz = new IO::Compress::Gzip($cache_file, Minimal => 1, 
AutoClose => 1, Append => 0) or return 0;
     print $gz $output;
   }

   $r->sendfile($cache_file);
   return OK;
}
1;
__END__



More information about the nginx mailing list