Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
nginx Perl Module to Output Content-MD5 HTTP Header
# nginx Embedded Perl module for adding a Content-MD5 HTTP header
#
# This perl module, will output an MD5 of a requested file using the
# Content-MD5 HTTP header, by pulling the hex hash from a file of the
# same name with .md5 appended to the end, if it exists.
#
# Author: Matt Martz <matt@sivel.net>
# Link: https://gist.github.com/1870822#file_content_md5_req_dot_md5.pm
# License: http://www.nginx.org/LICENSE
package ContentMD5;
use nginx;
sub handler {
my $r = shift;
my $filename = $r->filename;
return DECLINED unless ( -f $filename && -f "$filename.md5" );
my $content_length = -s $filename;
open( MD5FILE, "$filename.md5" ) or return DECLINED;
my $md5 = <MD5FILE>;
close( MD5FILE );
$md5 =~ s/^\s+//;
$md5 =~ s/\s+$//;
$md5 =~ s/\ .*//;
$r->header_out( "Content-MD5", $md5 ) unless ! $md5;
return DECLINED;
}
1;
__END__
# nginx Embedded Perl module for adding a Content-MD5 HTTP header
#
# This perl module, will output an MD5 of a requested file using the
# Content-MD5 HTTP header, by either pulling it from a file of the
# same name with .md5 appended to the end, if it exists, or will
# calculate the MD5 hex hash on the fly
#
# Author: Matt Martz <matt@sivel.net>
# Link: https://gist.github.com/1870822#file_content_md5.pm
# License: http://www.nginx.org/LICENSE
package ContentMD5;
use nginx;
use Digest::MD5;
sub handler {
my $r = shift;
my $filename = $r->filename;
return DECLINED unless -f $filename;
my $content_length = -s $filename;
my $md5;
if ( -f "$filename.md5" ) {
open( MD5FILE, "$filename.md5" ) or return DECLINED;
$md5 = <MD5FILE>;
close( MD5FILE );
$md5 =~ s/^\s+//;
$md5 =~ s/\s+$//;
$md5 =~ s/\ .*//;
} else {
open( FILE, $filename ) or return DECLINED;
my $ctx = Digest::MD5->new;
$ctx->addfile( *FILE );
$md5 = $ctx->hexdigest;
close( FILE );
}
$r->header_out( "Content-MD5", $md5 ) unless ! $md5;
return DECLINED;
}
1;
__END__
# nginx sample configuration for adding a Content-MD5 HTTP header
# using the Embedded Perl module
#
# Author: Matt Martz <matt@sivel.net>
# Link: https://gist.github.com/1870822#file_nginx.conf
http {
perl_modules perl/lib;
perl_require ContentMD5.pm;
server {
location / {
root /var/www;
index index.html
}
location /download {
perl ContentMD5::handler;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment