6.4. Limiting Upload Size
Problem
With more and more Web hosting services allowing customers to upload documents, uploads may become too large. With a little creativity, you can put a limit on uploads by using the security capabilities of the server.
Solution
Assume you want to put a limit on uploads of ten thousand (10,000) bytes. The simplest way to do this is to add a LimitRequestBody directive to the appropriate scope:
<Directory "/usr/local/apache2/uploads">
LimitRequestBody 10000
</Directory>If a user ties to send a request that’s too large, he’ll get an error message. However, the default Apache message may leave something to be desired so you can either tailor it with a ErrorDocument 413 directive, or with some more complex (and more flexible) jiggery-pokery such as the following:
SetEnvIf Content-Length "^[1-9][0-9]{4,}" upload_too_large=1
<Location /upload>
Order Deny,Allow
Deny from env=upload_too_large
ErrorDocument 403 /cgi-bin/remap-403-to-413
</Location>You can tailor the response by making the /cgi-bin/remap-403-to-413 script look something like this:
#! /usr/local/bin/perl # # Perl script to turn a 403 error into a 413 IFF # the forbidden status is because the upload was # too large. # if ($ENV{'upload_too_large'}) { # # Constipation! # print <<EOHT Status: 413 Request Entity Too Large Content-type: text/plain; charset=iso-8859-1 Content-length: 84 Sorry, but your upload file exceeds the limits set forth in our terms and conditions. EOHT } else { # # This is a legitimate ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access