# Minify and Gzip

**URL:** <https://www.ruby-forum.com/t/minify-and-gzip/210481>\
**Category:** NGINX\
**Created:** [August 9, 2011, 4:03pm UTC](https://www.ruby-forum.com/t/minify-and-gzip/210481 "2011-08-09T16:03:32Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![luislavena](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/l/0ea827/32.png) [@luislavena](https://www.ruby-forum.com/u/luislavena)\
**Post date:** [August 9, 2011, 4:03pm UTC](https://www.ruby-forum.com/t/minify-and-gzip/210481/1 "2011-08-09T16:03:32Z")

</div>

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](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**
