Search code examples
apache.htaccessgzipsetenvif

How do I disable GZip with SetEnvIfNoCase in Apache .htaccess?


I want to disable GZip for certain pages. I have this in my .htaccess, but it still turns GZip on (Content-Encoding: gzip) when visiting dashboard/index.

<ifmodule mod_deflate.c>
  AddOutputFilterByType DEFLATE text/text text/html text/plain text/xml text/css application/x-javascript application/javascript
  BrowserMatch ^Mozilla/4 gzip-only-text/html
  BrowserMatch ^Mozilla/4\.0[678] no-gzip
  BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
  SetEnvIfNoCase Request_URI /dashboard/index no-gzip dont-vary

I tried to add Header set MyHeader %{REQUEST_URI} to see what the Request_URI was, but it gave an Internal Server Error.

I also tried the regex dashboard/index, dashboard/index.*, "/dashboard/index", etc., and tried SetEnvIfNoCase REQUEST_URI ..., but GZip was still on.

If I comment #AddOutputFilterByType, then GZip is turned off.

I'm using Apache 2.4.16, Yii 2.0.7, PHP. I'm using FPM in production, so apache_setenv() is not available.


Solution

  • You're probably using rewrites to get rid of index.php in the URL. Due to the stage at which SetEnvIf runs during the request, index.php will be part of the Request_URI var used (which is distinct from %{REQUEST_URI}).

    It's nowadays quite common to not use PATH_INFO for rewrites, but just plainly rewrite to index.php, where code just reads the original REQUEST_URI info. In that case, Request_URI in SetEnvIf will be just "index.php", so you'd need to set a flag env var in a special dummy rewrite for that URL, and reference it later with a REDIRECT_ prefix (as there is an internal redirect stage on rewrites where mod_rewrite prefixes all existing env vars with REDIRECT_):

    RewriteRule ^dashboard/index - [E=no-gzip:1]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule . index.php [L]
    SetEnvIf REDIRECT_no-gzip 1 no-gzip
    

    There is a slightly less verbose way if you rewrite to PATH_INFO (so "/foobar" turns to "/index.php/foobar" using e.g. a RewriteRule (.*) index.php/$1 rule):

    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule (.*) index.php/$1 [L]
    SetEnvIfNoCase REQUEST_URI ^/index.php/dashboard/index.*$ no-gzip dont-vary
    

    But that seems more brittle since it'll break if you change the RewriteRule mechanics.