Back to Top

Saturday, June 14, 2008

Disabling mod_deflate for certain files

I received a question regarding my compressed HTTP post. It goes something like this:

I want to use a PHP script as a kind of transparent proxy (that is, when I request a file, it downloads it from an other URL and serves it up to me), but mod_deflate keeps eating my Content-Length header.

My advice is of course to selectively disable mod_deflate for the given PHP script. This would mean putting something like the following in your .htaccess file:

SetEnvIfNoCase Request_URI get_file\.php$ no-gzip dont-vary

Where get_file.php is the name of the script. Some things to remember here:

  • the dot character needs to be escaped, because it is a meta-character for regular expressions (meaning any character), so you must prefix it with a backslash to mean the dot character
  • Request_URI represents the URL up to the filename, but not including any query parameters. For example if you have the URL http://example.com/get_file.php?file=talk.mp3, Reques_URI will contain http://example.com/get_file.php. However be aware that Apache contains a nice trick which can be used to generate nice URL's but which can affect this: if the given file/directory is not found, it tries to go up the path to find a file. For example, I could have written http://example.com/get_file.php/talk.mp3, and if the script contains the logic to serve up talk.mp3, we can have a nice URL. The side effect is however that the Request_URI is now http://example.com/get_file.php/talk.mp3 and the regular expression must be adjusted accordingly (into something like \.mp3$)

A final word of warning: if your host allows you to open files via URLs (with readfile for example), run, run far away, because this is a very insecure configuration for PHP and chances are that the server (especially if it shared between multiple users) will be powned quickly.

4 comments:

  1. Anonymous6:35 PM

    I had the same problem on my download area, but I wasn't able to understand why. Thankyou so much!

    ReplyDelete
  2. I had the same problem and i was searching for this solution all over the web... A VERY BIG THANK YOU!!!

    ReplyDelete
  3. How would I disable mod_deflate for a whole directory rather than just a file?

    ReplyDelete
  4. @Alex: you can specify .* as the regular expression in the .htaccess file:

    SetEnvIfNoCase Request_URI .* no-gzip dont-vary

    HTH.

    ReplyDelete