CSS headers for gzipped php files

Odd one, I hope someone can help.

I’m using a PHP file to generate CSS, which I want to gzip before serving.

Here’s some example code:

<?php header('Content-type: text/css'); ob_start("ob_gzhandler"); ?>


Now, I know I don’t need the ob_gzhandler, as DH gzips. My problem is that if I include the text/css header then nothing is gzipped. If I leave it out then the file is compressed nicely, but the browser won’t recognise the css rules.

This is cross browser, and I’ve tried all sorts of combinations of different gzip methods, and the order of the headers but I just can’t get it to work. I’ve tried a link rel=stylesheet and an @import, and even meddled with .htaccess!

If I add the css header it won’t compress, if I leave the header out it will compress but will not be recognised as CSS.

(I have the same issue with javascript files, but at least the browser will still eventually figure out that it’s js…)

Is this a DH peculiarity or have I done something very silly?

pop this in your .htaccess:

<IfModule mod_deflate.c>
  <FilesMatch "\.(css|js|x?html?|php)$">
    SetOutputFilter DEFLATE

Might work

Or, simpler:

(The text/html type is already specified in the server configuration, so you don’t need to repeat it.)

Genius - thank you people!

My CSS is now compressed and recognised as CSS!

Doesn’t work for the javascript though:


<?php header('Content-type: application/x-javascript'); ?>

var stuff=ting;

If I have the header in it doesn’t deflate, if I take it out it doesn’t deflate or have the correct mime-type. It doesn’t massively matter as I can deflate with zlib.output_compression and the browser will figure out that it’s javascript but it’s good to get these things right if we can.

Thank you for your help!

I believe that AddOutputFilterByType determines the “type” of a file based on its extension, not on the final value of the Content-Type header, as Apache sets up output filters before it knows what the headers on the output will be. You’ll need to use a workaround like the one posted by bobocat above if the extension doesn’t match the final MIME type.

I get you. Thanks again!

not sure exactly what your main goal is, but if it’s just compression, I’ve tweaked this code to work with all CSS and JS on my site. I don’t put it in the CSS, but read ad the CSS files requested into this compressor and return the output:


that way CSS stays CSS and avoids confusing the IDE