Compress PHP, CSS, JavaScript(JS) & Optimize website performance.

Since few days we have been registering heavy traffic spikes on our website. This lead to performance issues. As this site is currently hosted on a shared hosting server, it is very difficult to optimize the performance of the site. We are using WordPress as CMS for this blog, hence we decided to install WP-Super cache plugin for WordPress to improve the performance. This plugin will create static HTML files from your blogs post and other pages and save them on web server. These HTMLs are served to client whenever consecutive requests are made. Hence this greatly improve the performance as it reduce PHP parsing and database connections. Bandwidth control is an important task to be followed when your traffic is increasing. With limited monthly bandwidth hosting, your site may run out of bandwidth and thus result in increase in down time. Hence it is very much advisable to compress your websites response with GZip and then serve it to client. Compressing output can significantly improve your websites performance by reducing the size sometimes upto 80%! So how can you enable GZip compression and compress your websites output? Well there are several ways to achieve this. I have listed out following very useful tricks to enable compression.

GZip compression in Tomcat, JBoss server

You can find a full post explaining this trick here.

GZip using mod_gzip, mod_deflate and htaccess

Apache server supports server level GZip compression with the help of module mod_gzip and mod_deflate. You can use this module and enable GZip compression for your website using htaccess file. First you have to check whether your hosting provider has enabled mod_gzip or mod_deflate module or not? To check this, you can use php_info() function of PHP which prints all the information about server and modules. You can enable compression for text and html by adding following lines in your htaccess file.
# compress all text and html: AddOutputFilterByType DEFLATE text/html text/plain text/xml # Or, compress certain file types by extension: <Files *.html> SetOutputFilter DEFLATE </Files>
Code language: HTML, XML (xml)
You can compress all type of content (image, css, js etc) using mod_deflate. Copy following code in htaccess to do this.
<Location /> SetOutputFilter DEFLATE SetEnvIfNoCase Request_URI \ \.(?:gif|jpe?g|png)$ no-gzip dont-vary SetEnvIfNoCase Request_URI \ \.(?:exe|t?gz|zip|gz2|sit|rar)$ no-gzip dont-vary </Location>
Code language: HTML, XML (xml)
Also, you can add following code in your htaccess file and enable compression using mod_gzip.
<IfModule mod_gzip.c> mod_gzip_on Yes mod_gzip_dechunk Yes mod_gzip_item_include file \.(html?|txt|css|js|php|pl)$ mod_gzip_item_include handler ^cgi-script$ mod_gzip_item_include mime ^text/.* mod_gzip_item_include mime ^application/x-javascript.* mod_gzip_item_exclude mime ^image/.* mod_gzip_item_exclude rspheader ^Content-Encoding:.*gzip.* </IfModule>
Code language: HTML, XML (xml)
This technique only works if mod_gzip or mod_deflate modules are loaded in Apache. In our case, these modules were not there and our hosting provider refused to load it as we were using a shared hosting. So following can be another way of enabling compression.

GZip using PHP ob_start() method

If your hosting provider does not support mod_gzip module, ob_start() method can be used to enable compression in PHP file. For this you need to copy following line in top of the PHP file. You may want to add this line in start of the header file that gets included in every php.
if (substr_count($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip')) ob_start("ob_gzhandler"); else ob_start();
Code language: PHP (php)
Above code will check whether your browser supports gzip, if yes, then it send ob_gzhandler method as handle to ob_start method which buffers the output. Thus output is compressed using ob_gzhandler. Only problem with this method is that you have to manually edit all PHP files or should have a header.php file that gets included in all files. There are still ways to achieve this without touching your PHP files. Read following trick.

GZip using php_value directive in htaccess

php_value directive can be used to append/prepend any PHP files in the request of change the output handler. First we will see how we can prepend a PHP file and achieve this. Copy the PHP code that we saw in above example in a file called gzip-enable.php. Now copy following lines in your htaccess file. Thus you need not to modify any of your PHP files can can prepend a PHP file with ob_start() method to all the files.
<FilesMatch "\.(txt|html|htm|php)"> ForceType application/x-httpd-php php_value auto_prepend_file /the/full/path/gzip-enable.php </FilesMatch>
Code language: HTML, XML (xml)
But what if you don’t want to prepend a PHP file? Still there is a way to specify default output handler using htaccess. Use following line in your htaccess file to tell your apache to register ob_gzhandler handler function as output handler.
php_value output_handler ob_gzhandler
Code language: HTML, XML (xml)

Compress CSS using htaccess and php_value

CSS Stylesheet files occupy significant size in overall webpage size. It is hence advisable to compress these files before sending them to client. This significantly improve the performance of a webpage. For compressing CSS files, we will first create a PHP file gzip-css.php with following code.
// initialize ob_gzhandler function to send and compress data ob_start ("ob_gzhandler"); // send the requisite header information and character set header ("content-type: text/css; charset: UTF-8"); // check cached credentials and reprocess accordingly header ("cache-control: must-revalidate"); // set variable for duration of cached content $offset = 60 * 60; // set variable specifying format of expiration header $expire = "expires: " . gmdate ("D, d M Y H:i:s", time() + $offset) . " GMT"; // send cache expiration header to the client broswer header ($expire);
Code language: PHP (php)
Now add following lines in your htaccess file to enable compression for CSS files.
<FilesMatch "\.(css)"> ForceType application/x-httpd-php php_value auto_prepend_file "/the/full/path/of/this/file/gzip-css.php" </FilesMatch>
Code language: HTML, XML (xml)
Whenever a http request for .css will come to a server, the type of css will get converted to application/x-httpd-php, thus making them parsed using PHP. Then a file gzip-css.php will be prepend to this request which in turns compress the output using ob_start (“ob_gzhandler”) method.

Compress JavaScript (JS) using htaccess and php_value

Similar to above example for CSS, JavaScript files can also be compressed and sent to client. For this create a PHP file gzip-js.php and copy following code in it.
// initialize ob_gzhandler function to send and compress data ob_start ("ob_gzhandler"); // send the requisite header information and character set header ("content-type: text/javascript; charset: UTF-8"); // check cached credentials and reprocess accordingly header ("cache-control: must-revalidate"); // set variable for duration of cached content $offset = 60 * 60; // set variable specifying format of expiration header $expire = "expires: " . gmdate ("D, d M Y H:i:s", time() + $offset) . " GMT"; // send cache expiration header to the client broswer header ($expire);
Code language: PHP (php)
Also add following lines in your htaccess file.
<FilesMatch "\.(js)"> ForceType application/x-httpd-php php_value auto_prepend_file "/the/full/path/of/this/file/gzip-js.php" </FilesMatch>
Code language: HTML, XML (xml)
Do you know other methods of compressing the output of PHP/JS/CSS files? Let me know, I will try to add them in this tutorial. Happy Compressing :)
Get our Articles via Email. Enter your email address.

You may also like...


  1. Gaurav says:

    Nice picture dude..!!!

  2. Good stuff! Remember, though, that you are preventing your users from caching your CSS and JS. You should check your ratio of new/returning visitors before considering this.

  3. Disaster says:

    Awesome article, thanks! Will come in handy in future projects :)

  4. @Gaurav, Thanks for the comment.

    @Eric, I forget to mention it in this tutorial. Thanks for pointing this out. I will update the post.

    @Disaster, You welcome :) You can bookmark this tutorial if you find it useful.

  5. nightS says:

    Thank you so much!

  6. Great article…!

  7. carson says:

    It sounds good news to me. But in Joomla 1.5 there seems no effect….
    Is it also worked in Joomla! 1.5 with sef enabled?

  8. Hi Carson,
    I have not tried this with Joomla, but I think it will work as these are the normal rules under htaccess file. These rules are applied after Joomla sends the output.

  9. Tejas Mehta says:

    Hi Viral,
    Nice tutorial. I would like to know that if there any solution to view this compressed file as normal file ? i have tons of files which are compressed. i need to modify their code for my purpose but due to files are compressed. i am not able to do it. if you know than let me know.


  10. Deepak G says:

    Thanks Viral,

    It helped me also.

  11. Steffen says:

    Thanks for that great article! It really helped me understanding the whole thing!
    But I’m wondering why you’re not caching images? What’s the reason for it, as images normally don’t change?

  12. It helps me a lot.


  13. Great Post man..

  14. Paul says:

    What about if you have multiple javascript calls on the one page? I get errors

    I used the last methods for css and also javascript (ie creating .htaccess entry and php file)

    Error Says:
    <b>Warning</b>: ob_start() [<a href=\’ref.outcontrol\’>ref.outcontrol</a>]: output handler \’ob_gzhandler\’ cannot be used twice in **file name**

    Does anyone have a way of helping me out of this predicament.


  15. Balaji says:

    Thanks for the nice post. But I am facing a problem with IE6 accessing gzip contents(css/javascript files). The apache web server sends gzip contents correctly, but the IE6 doesnt seem to pick gzip contents up. I tried HTTP Analyzers to debug further and I could clearly see that the header option “Accept-Encoding” is missing. I dont have any idea how to include this header option through javascript.
    Now I suspect the following.
    1) Any IE6 security updates are restricting compressed contents to be read/parsed?
    2) Any windows firewall options or firewall softwares or antivirus softwares are restricting the compressed contents?
    3) Or is there any other windows softwares that restrict due to security reasons?
    If yes, Could any one of you please give me a list of applications that might impose such a restriction.

    Am using IE6.0.2900.5512.xpsp_sp3_gdr.090206-1234

    Many thanks

  16. Hi Viral,
    First of all, thanks for the wonderful tutorial.You have made my day. I was tweaking and searching for the whole day on this issue, but now looks like I have got a sulution.

    I am using powweb as my host and they do not support gzip module.

    I tried your \"GZip using php_value directive in htaccess\" but it failed.
    Even on making a new gzip-enable.php and modifying htaccess, I get server internal error.

    I find that your pages are gzipped, which medhod do you use?

    Any help will be highly appreciated.

  17. Hi Abhishek,
    Try to add following entry in your .htaccess file and see if it is working.

    <FilesMatch "\.(txt|html|htm|php)">  
    	php_value output_handler ob_gzhandler  

    You may want to add css and js in the FileMatch tag to add gzip compression to css and js files.

    Hope this will work.

  18. fakhruddn says:

    nice article it helps me a lot
    but i dont know why IE7 does not display any thing it says “Internet Explorer cannot display the webpage” it works fine in firefox but does not displaying model dialog..
    and it work fine in opera and chrome can any body suggest me what i did wrong…

  19. Abhishek says:

    Thanks tht was helpful!! :)

  20. Arthur says:

    Has anyone else tried this in firebug to check for caching??? It works on JS files but not on the CSS?? What am I doing wrong?

  21. hen says:

    ANY OF THESE TIPS Doesnt work in

    I have tried the compressing of css by doing what you said :)

    i create a gzip-css.php put it in my root and insert

    Then after that i copy pasted

    ForceType application/x-httpd-php

    php_value auto_prepend_file “/the/full/path/of/this/file/gzip-css.php”

    into my .htaccess I edited the path of course

    THE RESULT? error 500? internel server error

    hope you can reply on this one. thanks

  22. Green Card says:

    Hi Viral,
    My hosting enviroment does not suport gzip either so I was very happy to read your article. i immediatly tried to implement it but got a http-500 error immediatly.
    I created the file gzip-enable.php and included this in the .htaccess file

    <FilesMatch \"\\.(txt|html|htm|php)\">
    ForceType application/x-httpd-php
    php_value auto_prepend_file /includes/gzip-enable.php
    Then i refreshed my browser and got the 500 error. All my pages are php pages with css and java scripts. Is there something I am missing here?

  23. @Green Card, @hen
    Try to add following entry in your .htaccess file and see if it is working.

    	php_value output_handler ob_gzhandler
  24. Green Card says:

    That worked :-)
    Thanks Viral,

  25. Although shared hosting is a less expensive way for businesses to create a Web presence, it is usually not sufficient for Web sites with high traffic. These sites need a dedicated Web server, either provided by a Web hosting service or maintained in-house. With shared hosting, numerous web sites are sharing a single server.

  26. haberler says:

    really helpful article i bookmarked this page.Thanks again.

  27. cock says:

    thisi is good??????????????????? ya really good

  28. @Green Card, @haberler, @cock
    Thanks for the comments :)

  29. Philza says:

    Mmmm, I had the exact same issue – I started to get regular hits/spikes of very high traffic, part of growth I guess but it slowed my website to a crawl for many visitors. I too use wordpress – had tried the plugins and they just weren’t enough. When you’re running a site that is growing ultimately you need to consider a dedicated server in order to continue to grow. My site is also hosted in the US but my visitors are international so I needed to consider latency. Moving to a dedicated server increases your options for web performance optimization enormously (as does the cost…sigh…) my host also included a website accelerator called Aptimize and that has really put my site in another league, its now lightening fast and scales the traffic spikes excellently. It really a positive that your dealing with this issue as it is a sign of success.

  30. Jef says:

    Thanks for the post, I will look for some of these hint!

  31. anparasu says:

    ForceType application/x-httpd-php
    php_value auto_prepend_file “gzip-css.php”
    php_value output_handler ob_gzhandler

    I have added the above code in the .htaccess file. also created the gzip-css.php file. both files are in the root directory. but after placing this css is not working.
    Any ideas what i have done wrong ?

  32. Alwi says:

    Woww … very nice posting, I need this post to performance on my blog, and thank …

  33. Kris says:

    Hello Viral
    I have a very serious problem. As per your posts i added the following in htaccess

    php_value output_handler ob_gzhandler

    php_value output_handler ob_gzhandler

    ForceType application/x-httpd-php
    php_value auto_prepend_file “”

    Instantly I’m getting internal Server Errors. Pls Pls help. I’m on Hostgator Business Hosting.

  34. Anparasu says:

    Hi Kris,

    I too faced the same problem and find out that this method wont work if you have apache module PHPSUEXEC installed to your server.

    You can find the solution after reading the url above.

  35. satefan says:

    Paul>> It was a while ago your wrote that, but maybe someone else will encounter that error. I hHad the same problem. Removed the line
    ob_start (“ob_gzhandler”);
    from the js./css.php files and then it worked fine.

  36. trv ajans says:

    very god

  37. It was nice post and I tried to use them. But I noticed error or no effect of compression while implementing on the websites hosted on shared server. So which one works best for shared one?

  38. Thanks very informative article.

  39. Amal Roy says:

    Thanks for the tips friend.
    But doesnt the w3cache and super cache plugin have these option in it to do it automatically?
    I my opinion using a CDN network would speed up wordpress drastically. But since the cdn network is expensive, there is also a free cdn service i think.

  40. Incredible I got IE rendering faster then Firefox ;-) until 20 mins ago I would have lost my head , children, car and whatever telling : ” THIS CAN NEVER BE… ” Now I will tell you how ….

    First of all thanks… for your info…

    I could just use the php compression as Java compression killed the same java and dom employment..

    but I got fine results :

    without anything Page size :Total Size: 400071 bytes HTML: 94440 Javascript: 284778
    Connection Rate Download Time

    28.8K 160.04 seconds
    56K 84.73 seconds
    ISDN 128K 29.42 seconds
    T1 1.44Mbps 7.12 seconds

    With the php header Total Size: 320897 bytes HTML: 15266 Javascript: 284778

    Connection Rate Download Time

    28.8K 129.36 seconds
    56K 68.95 seconds
    ISDN 128K 24.59 seconds
    T1 1.44Mbps 6.70 seconds

    In those cases a small trick to enhance a lot loadtime :

    include_dom(divname,javasciptname); (just google the sourcecode)

    The results here : Total Size: 70008 bytes HTML: 15261 Javascript: 33894

    Connection Rate Download Time

    28.8K 31.33 seconds
    56K 18.15 seconds
    T1 1.44Mbps 4.57 seconds

    Now the explanation and trick ;-)

    IE 7 / 8 has an internal coding translating whatever dom / java code into a proper language, changing whatever, even variable names, therfore such many exceptions and bugs…. and especially 3 times time more to render java and dom enhanced media.

    Useless to tell you that Firefox, Chrome and Safari do not work that way, so they perform much faster.

    In any case however they work, they parse the java code fully before executing it, so it is loaded and whatever will happen to the page on the client, just thenafter…

    Even if you place in your Javacode a call like ” include_dom(divname,javasciptname) ” somewhere in the code, they do not get fooled at all, and will load that program or programs before rendering.

    But if you trick it the way :

    var I_have_loaded_my_java_programs = false;

    and then somewhere later

    if(I_have_loaded_my_java_programs == false) {

    I_have_loaded_my_java_programs = true;

    Then all browsers get tricked and start rendering immediately… all opera, chrome, internet explorer except firefox, who is that smart not to be fooled ;-)

    The difference is great, as the rendering starts in one second or less (with an empty cache in your browser), so you start over to see something on the webpage within a second. Well Firefox needs now a bit longer, so 2 seconds and amazingly IE 7/8 performs same as Chrome and Safari… (never use IE on Java espescially when working on the DOM Model, I experienced even timeout warnings on complicated models…)

    So lot’s of thanks to your writing I got that way from 7.12 seconds to 6.7 seconds, and as a thanks to my trick bringing the same page to 4.57.

    To see it in action, I’ll move it down today to root level on , and by the way I guess lots of you will like, what you find there, this beyond testing and speed reduction.

    Thanks to whoever reads it and gets a nice impression, thanks to for the guide.
    Quasiamodo, Italy

    • @Claudio Klemp: wow.. thats really a comprehensive list. Thanks for sharing this info. Much appreciated :)

  41. Avinash says:

    Hi Viral,

    Here gzip not installed so i have tried below things.

    Included above code to all files.

    php_value output_handler ob_gzhandler

    Placed above code in my .htaccess file.

    But still i getting warning msg to compress the php, css and js code using gZip.
    I am getting this error in ySlow addon of the mozila firefox.

    Is there something i am missing.


  42. Elijah says:

    Thanks lot,very useful….

  43. Vaibhav says:

    Hey Viral,

    I tried your last two methods:
    1.Compress CSS using htaccess and php_value &
    2.Compress JavaScript (JS) using htaccess and php_value

    This method is working for css but not working of Javascript.
    I have slideshow that uses Jquery, and thats not working after applied compression.
    Could u help me out please

    Thanks & Regards

  44. Thanks for sharing so much interesting details with us.

  45. Thank you. Very Useful tips.

  46. hana says:

    in this web site one company did that after that gave us CMS to change but when open it in firefox display message as calander.setup nothing to setup. also when change in cms and then save it , and check it that is not change. i don’t know what the problem.
    please how i can solve this problem. help me

  47. rangga says:

    nice, I’ll try if there is trouble I beg explanation

  48. alessandro says:

    does not work… I have in my .htaccess:

    ForceType application/x-httpd-php
    php_value auto_prepend_file “[my path to gzip-css.php]”

    When my css files are downloaded, they have “Content-Type:text/html” and the css content is not applied to the document.

  49. Mitran says:

    i want to learn how to write a basic htaccess file for our own site… is it possible???

    any ref links?????????????????

  50. John says:

    Thanks for your article. our website loaded quite slow. I hope this will help to speed it up.

  51. Arn says:

    Your article served as part of the basis for my newly created offline (batch) script that creates combined, minified and gzipped JS and CSS files. Files are pre-gzipped so no server overhead for compression every time file is served. More info at

  52. Maskukuh says:

    Nice tutorial.. i’ll try this for my web blog.. thanks

  53. Jasper says:

    You could also minify them in PHP a different way.
    I do it this way:

    The user, always gets just the minified version with no checking (or just every week or so)
    The developer, sets a cookie by logging in as admin, and therefore a filemtime check is done every call, on all the css / js files.
    If they are expired, the minified version gets rebuilt..
    With minified version I mean, all the files combined into one file. Saves about 10 requests in my case :)
    I then gzip this file too.
    // write minified file
    $f = fopen( $outfile , ‘w’ );
    if ( $f ) {
    fwrite( $f, $output );
    fclose( $f );
    $path = realpath($outfile);
    $cmd = “gzip -9 $path -c > $path.gz”;
    I combine this with an htacces trick, to get the scripts and styles served Gzipped, STATICALLY :)

    AddEncoding x-gzip .gz
    ForceType text/javascript
    Header set Vary Accept-Encoding

    AddEncoding x-gzip .gz
    ForceType text/css
    Header set Vary Accept-Encoding

    RewriteCond %{HTTP_USER_AGENT} !”.*Safari.*”
    RewriteCond %{HTTP:Accept-encoding} gzip
    RewriteCond %{REQUEST_FILENAME}.gz -f
    RewriteRule ^(.*)\.js $1.js.gz [L,QSA]

    RewriteCond %{HTTP_USER_AGENT} !”.*Safari.*”
    RewriteCond %{HTTP:Accept-encoding} gzip
    RewriteCond %{REQUEST_FILENAME}.gz -f
    RewriteRule ^(.*)\.css $1.css.gz [L,QSA]

    This performance difference is another 20-25ms per file, measured on Zend server CE linux, on a core2duo e6300 @ 3ghz.

    • Jasper says:

      Oh i forget about the cache part:
      foreach($files as $file)
      $file = $realpath.$file;
      if ( is_file($file) && $mtime = filemtime($file))
      $mtimes[] = $mtime;
      } }
      $hash = md5(json_encode($mtimes));
      if(!$hash_compare = $this->cache->get($hash,false))
      $has_been_modified = true;

  54. Tamik says:

    Nice tutorial. But i think doing a compression on server side is a bit overhead on server load. I prefer to compress files once and then just show the compressed version, the online tool can help avoid annoying manual compression.

  55. Roman says:

    I compress my CSS only once with my own created css compressor:

    but thanks for tut, anways <3

  56. I am using to compress all of css. Its quick and easy to use online. Just try and see.

    • Hello… They wont compress it they will just removes the whitespace and change some code. But if yo want to gzip it than you have to use gzip method for css

  57. Manado says:

    nice trik. thankyou brother. i will do this on my website

  58. Parvaiz says:

    i have installed a script on my website for compression on run time, it works fine but when i check , is it compressed or not i found it is compressed on but on other sites i do not find my website is compressed i do not know which is right.

  59. Faizan says:

    What a dumbass trick

    • Faizan says:

      We all have very good internet connections and save 2KB is not worth enough

  60. Boris says:

    I get server error 500… when I try to “Compress CSS using htaccess and php_value”. What could be wrong?

  61. Excellent article, but there’s a slight mistake in some of the “Content-Type” headers. The syntax is:
    Content-Type: [MIME]; charset=utf-8
    Some of the examples use a colon to determine the value for charset— e.g.: charset:utf-8 — where as it should be an equals sign.
    Great article, though — I am definitely going to get this up-and-running on my site.

  62. P.S. My hosts, A Small Orange, have upgraded the server to PHP5. I’ve noticed that this seems to have caused problems with the “php_value” directive. Does anyone know any way around this, without having to edit into the php.ini file? (My site’s a host that uses a shared server.)

  63. techlib says:

    Very useful post. I could save good amount of bandwidth using this. Thanks :)

  64. nice trick. thanks

  65. Awesome article, thanks!
    very nice posting, I need this post to performance on my blog.
    it Will come in handy in my coming projects.

  66. Raj says:

    thanks bro

  67. Sachin says:

    Big thanks friend.. it worked like a magic specialy for my css files.. It also increased site score in google speed test.
    Big Thanks, pls keep up your great work..

  68. David Spencer says:

    How to enable compression for webhost like ??

    While I have contacted to them they reply like this,

    Our servers support mod_gzip, mod_deflate by default.

    To use GZIP, please call the function ob_start(“ob_gzhandler”); at the top of your script. Also remember to call the function ob_flush(); at end

    Can you please explain it how to do gzip it in ?

    Please explain steps easily, I am not much technical person.

  69. Bhumi says:

    Great tutorial.

  70. Dan says:


    I getting 500 internal error for using “Compress CSS using htaccess and php_value”. my host is 1and1. Can you please help me,


  71. Sumeet says:

    Hi Please tell me the process for compression in nginx server and in django frame work.
    Is there any file that works similar that htaccess does in apache in nginx server

  72. Utpal says:

    Please tell me how we will implement it in nginx server with multiple server blocks.

  73. Innocent Cyril says:

    I so much thank you for this great help thanks alot

  74. debolina says:

    wow very nice article thank you

Leave a Reply

Your email address will not be published. Required fields are marked *