Web-en

Fix Google PageSpeed enable compression in PHP and htaccess

Enabling gzip compression on your script / webserver will not only help you achieving a greater score on Googleicon PageSpeed “Enable compression” [1] test, but also allow a faster rendering time on your visitors browser.

The easiest way to achieve it, providing your are using PHP, is to add a few lines at the beginning of your PHP script to activate zlib output compression [2] :


ini_set("zlib.output_compression", "On");
ini_set("zlib.output_compression_level", "-1");

A good way to check if it works, is to perform a before / after test on gidnetwork (Fig 1) [3] for example.

Gidnetwork.com GZIP compression test tool
Fig 1 : Gidnetwork.com GZIP compression test tool

You can also add the following piece in your htaccess file, which will tell Apache to compress the corresponding files, providing the mod_deflate is activated on your server :


#Compression
<IfModule mod_deflate.c>
    AddOutputFilterByType DEFLATE text/text text/html text/plain text/xml 
	text/css text/javascript application/javascript
</IfModule>

For more details on Apache compression, please see the great articles about this subject on betterexplained.com [4] or www.cloudtech.ch [5].

For example, this allowed me to pass the Googleicon PageSpeed [6] test Enable Compression [1] on a website, going up from a score of 72 on mobile (Fig 2) to 89 (Fig 3), and up from 79 (Fig 4) to 89 on desktop (Fig 5).

Google Page Speed - Score before activating gzip compression of 72 on mobile
Fig 2 : Google Page Speed – Score before activating gzip compression of 72 on mobile
Google Page Speed - Score after activating gzip compression of 89 on mobile
Fig 3 : Google Page Speed – Score after activating gzip compression of 89 on mobile
Google Page Speed - Score before activating gzip compression of 79 on desktop
Fig 4 : Google Page Speed – Score before activating gzip compression of 79 on desktop
Google Page Speed - Score after activating gzip compression of 89 on desktop
Fig 5 : Google Page Speed – Score after activating gzip compression of 89 on desktop

Links and credits

  • [1] – Optimizing encoding and transfer size of text-based assets — Web Fundamentals – developers.google.com
  • [2] – PHP: Runtime Configuration – Manual – php.net
  • [3] – GIDZipTest: Web Page Compression (Deflate / Gzip) Test – GIDNetwork – www.gidnetwork.com
  • [4] – How To Optimize Your Site With GZIP Compression | BetterExplained – betterexplained.com
  • [5] – Mod_deflate compressing html javascript and css files | cloudtech GmbH – www.cloudtech.ch
  • [6] – PageSpeed Insights – developers.google.com

Images