The Correct Way To Set Up gzip with Magento

We wrote this arti­cle in response to post­ings offer­ing advice to users of Magento, an open source ecom­merce sys­tem. The advice is being given with good inten­tions, and the intent is only to assist their fel­low Magento users. But the advice being give may actu­ally have the poten­tial cause harm to the users site, or at the least a good deal of down time. The advice being offered is to help speed up Magento by enabling a server side caching sys­tem called gzip. What peo­ple don’t real­ize is that their being told to enable two sep­a­rate caching sys­tems. These two sys­tems tend not to play well together, and could cause harm to your install. While most peo­ple see pos­i­tive results, there are a rare few see­ing server side errors, data­base errors, and are stumped as to why.

The two caching sys­tems are gzip and zlib. Most rep­utable host­ing com­pa­nies include these options in their shared host­ing pack­ages. By default most of these options are dis­abled. We’re going to show you the right way to setup caching on your server, and at the same time solve the dreaded recur­ring mem­ory issues that have plagued so many Magento users. Our setup is as fol­lows. A shared host­ing account on Hostmonster.com, a fresh Magento install, cur­rently the lat­est ver­sion 1.3.2.4. and the gzip caching.

The major­ity of peo­ple read­ing this will be on a sim­i­lar shared host­ing account, so this will be our focus. If you don’t already know whether gzip is avail­able on your server, copy the fol­low­ing code to an html edi­tor, or a text edi­tor, and save it as test.php

1
2
3
<?php
phpinfo();
?>

Upload the file to your server, and nav­i­gate to it with your web browser. If you see gzip any­where on the info page, you’re in luck. Remem­ber to remove this file before mov­ing on, as it does pose a secu­rity threat if left on the server.

Next you need to log into you host­ing account and access your cpanel. Keep in mind that most good host­ing com­pa­nies will help you with all of this, so never be ashamed to ask for help.

Before going any fur­ther, you should also be absolutely pos­i­tive that all your sites can run on PHP5. If not you’ll want to upgrade any scripts uti­liz­ing an older ver­sion of php. Now we need to install a sin­gle default ini, php.ini.default, via your cpanel. Nav­i­gate to the the php admin area. Choose to install a (Sin­gle php.ini) Choose save, then scroll down to the check­boxes for Ion­Cube and Source­Guardin, and click “Install php.ini Mas­ter File”. This man­u­ally directs sys­tem resources to the new loca­tion of your sin­gle php.ini file. Call your host if you need help. Now down­load the file that was just cre­ated from the root direc­tory of your server ( php.ini.default ) Rename this file to php.ini and open it.

First locate the mem­ory set­tings, cur­rently located on line 225, and dupli­cate the set­ting bel­low. Your loca­tion may vary. Note, the char­ac­ter # before a state­ment means that won’t be read by the server, and has been “com­mented out”.

225
226
227
228
229
230
231
;;;;;;;;;;;;;;;;;;;
; Resource Limits ;
;;;;;;;;;;;;;;;;;;;
 
max_execution_time = 60     ; Maximum execution time of each script, in seconds
max_input_time = 120	; Maximum amount of time each script may spend parsing request data
memory_limit = 128M      ; Maximum amount of memory a script may consume (64MB)

Change the default mem­ory from the whop­ping default of 32m to a min­i­mum of 64m in a busy envi­ron­ment, or prefer­ably to some­thing like 128m, or even 256m if run­ning a siz­able store on a stand­alone server. Set­ting the ram too high can lead to sys­tem insta­bil­ity, loss of per­for­mance, and even a loss of priv­i­lege stem­ming from an inter­ven­tion by your sys­tem admins. With this ini in place, you’ve now set a global mem­ory set­ting across all fold­ers on your server. This is a sure fire way to elim­i­nate freez­ing dur­ing check­out, and other ran­dom Magento weirdness.

While here, you may also want to increase server exe­cu­tion time. While not nec­es­sary, espe­cially with our now increased Ram, our sug­ges­tion would be to dou­ble or triple the cur­rent set­tings. If you’ve got a script run­ning longer than a few min­utes, there’s prob­a­bly some­thing wrong, and a forced stop is in order.

Now that we’re uti­liz­ing more mem­ory, and have improved over­all sta­bil­ity and reli­a­bil­ity, it’s time to really make this thing boo­gie. With our default php.ini still open, search for ob_gzhandler This is also an area where you’ll see the use of either gzip or zlib, and never both. At the time of this tuto­r­ial the state­ment we’re inter­ested in uncom­ment­ing is located on line 106. Your loca­tion may vary. Note, like # in our .htac­cess, ; means that any state­ment fol­low­ing this char­ac­ter isn’t read by the server, and is “com­mented out”.

87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
; Output buffering allows you to send header lines (including cookies) even
; after you send body content, at the price of slowing PHP's output layer a
; bit.  You can enable output buffering during runtime by calling the output
; buffering functions.  You can also enable output buffering for all files by
; setting this directive to On.  If you wish to limit the size of the buffer
; to a certain size - you can use a maximum number of bytes instead of 'On', as
; a value for this directive (e.g., output_buffering=4096).
output_buffering = Off
 
; You can redirect all of the output of your scripts to a function.  For
; example, if you set output_handler to "mb_output_handler", character
; encoding will be transparently converted to the specified encoding.
; Setting any output handler automatically turns on output buffering.
; Note: People who wrote portable scripts should not depend on this ini
;       directive. Instead, explicitly set the output handler using ob_start().
;       Using this ini directive may cause problems unless you know what script 
;       is doing.
; Note: You cannot use both "mb_output_handler" with "ob_iconv_handler"
;       and you cannot use both "ob_gzhandler" and "zlib.output_compression". 
output_handler = ob_gzhandler
 
; Transparent output compression using the zlib library
; Valid values for this option are 'off', 'on', or a specific buffer size
; to be used for compression (default is 4KB)
; Note: Resulting chunk size may vary due to nature of compression. PHP 
;       outputs chunks that are few hundreds bytes each as a result of 
;       compression. If you prefer a larger chunk size for better 
;       performance, enable output_buffering in addition.
; Note: You need to use zlib.output_handler instead of the standard
;       output_handler, or otherwise the output will be corrupted.
zlib.output_compression = Off
 
; You cannot specify additional output handlers if zlib.output_compression
; is activated here. This setting does the same as output_handler but in
; a different order.
;zlib.output_handler =

Notice here that zlib is either com­mented out, or off. Be sure it stays this way.

Some­thing else worth men­tion­ing is the addi­tion of the fol­low­ing state­ments to your ini file. As of this tuto­r­ial, the fol­low­ing state­ments were added to our php.ini by default. But if your host­ing provider isn’t as proac­tive, they may be miss­ing. If so add them some­where near the bot­tom of your ini file as follows.

1125
1126
1127
1128
extension=pdo.so
extension=pdo_sqlite.so
extension=sqlite.so
extension=pdo_mysql.so

We’ve now fin­ished edit­ing our PHP.ini. Upload the file back to the root of your server. This one file pro­vides the sin­gle largest per­for­mance and sta­bil­ity improve­ment you’ll find with Magento.

Next retrieve your .htac­cess file from the root of your Magento install. Dupli­cate the set­tings you see below, and again upload the file back to the root of your server.
Mem­ory settings:

33
34
35
36
37
38
39
40
############################################
## adjust memory limit
 
#    php_value memory_limit 64M
    php_value memory_limit 128M
    php_value max_execution_time 18000
 
############################################

GZip uti­liza­tion:

78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
############################################
## enable apache served files compression
## http://developer.yahoo.com/performance/rules.html#gzip
 
    # Insert filter on all content
    SetOutputFilter DEFLATE
    # Insert filter on selected content types only
    AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css text/javascript
 
    # Netscape 4.x has some problems...
    BrowserMatch ^Mozilla/4 gzip-only-text/html
 
    # Netscape 4.06-4.08 have some more problems
    BrowserMatch ^Mozilla/4\.0[678] no-gzip
 
    # MSIE masquerades as Netscape, but it is fine
    BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
 
    # Don't compress images
    SetEnvIfNoCase Request_URI \.(?:gif|jpe?g|png)$ no-gzip dont-vary
 
    # Make sure proxies don't deliver the wrong content
    Header append Vary User-Agent env=!dont-vary
 
</IfModule>
 
<IfModule mod_ssl.c>
 
############################################

Also look at the top of your .htac­cess file. If you don’t see the fol­low­ing, and you’re sure you’ve setup your server to use a sin­gle php.ini by default, add the following.

1
2
3
4
5
6
7
8
9
10
11
# Use PHP5 Single php.ini as default
AddHandler application/x-httpd-php5s .php
############################################
## uncomment these lines for CGI mode
## make sure to specify the correct cgi php binary file name
## it might be /cgi-bin/php-cgi
 
#    Action php5-cgi /cgi-bin/php5-cgi
#    AddHandler php5-cgi .php
 
############################################

This would be a good time to remove any extra php.ini or .htac­cess files you’ve loaded to mis­cel­la­neous direc­to­ries in an attempt to improve Magento’s sta­bil­ity, some­thing we our­selves were guilty of.

And that’s it, within a minute of upload­ing your .htac­cess file you’ll be serv­ing, gziped files with a com­pres­sion ratio of 70–90 per­cent. Be sure to check that all scripts being served prop­erly, and are func­tion­ing nor­mally. Com­pres­sion may cause some scripts to behave errat­i­cally, or even cause pages to load jum­bled con­tent. To find out exactly what your com­pres­sion ratio is, visit any of the sites below and input your web­site url.

GZip Test­ing Sites

  1. GZip Dis­crim­i­na­tion Test
  2. Whatsmyip

We hope this arti­cle was help­ful, and if you think we’ve missed any­thing, let us know. Thanks for stop­ping by.



Was this article helpful? Here's a few related articles which may also interest you.

Related Posts:


8 Comments to “The Correct Way To Set Up gzip with Magento”

  1. Yurii says:

    Thank you so much!!!!!!!!!!!!!

    I had the hard­est time get­ting gzip to work right. I went through every­thing you wrote. I tried it and its work­ing!! What a huge dif­fer­ence in load times. I was start­ing to think Magento just had errors out of the box. But this fixed it. Thank you!!!!!

    Did I men­tion? Thank you. Thank you. Thank you. Thank you. Thank you. Thank you. Thank you. Thank you.

  2. Duarte Netto says:

    Hi,

    I’ve just enabled the Gzip on the server (win 2003 stan­dard with iis 6).

    Now, i have con­firmed that the server as the Gzip acti­vated with the test to a domain in the same server but when i try to test it on the Magento domain…it inst activated.

    Test Tool
    http://www.whatsmyip.org/http_compression/

    Domain in the same server
    http://directo.tr2k.com/login.aspx

    Domain with MAGENTO
    http://www.rockartstore.com/index.php/

    The .htac­cess doest work on IIS so that’s not a solution…iv tried in the php.ini only seems to work on Apache.

    Any sug­ges­tions?

    Is there a place were i can enable it in the admin panel?

  3. Fertiliser says:

    Best ver­sion so far as men­tion­ing that the php.ini require­ments did the trick for me. Is output_handler = ob_gzhandler bet­ter than zlib.output_compression as both are enabled on my server?

    I installed yslow and it shows about 19 .css and .js files are not sent com­pressed eg. /js/prototype/prototype.js and /css/reset.css but the main site is gziped http://www.biostim.com.au . Is there any­way to get them com­pressed also.

    I tried to Minify JavaScript and CSS with Foomans speed­ster exten­sion http://www.magentocommerce.com/magento-connect/FOOMAN/extension/457/fooman-speedster but my theme didn’t work too well so I unin­stalled it.

    To Add Expires head­ers I put the below into .htaccess(after # Make sure prox­ies don’t deliver the wrong con­tent
    Header append Vary User-Agent env=!dont-vary </IfModule) but a few files still didn’t change eg /skin/frontend/default/biostim/favicon.ico

    “Code Edited Here. Revised Code Posted in Reply Below.…”

    Thank you for the post.

    Kind regards
    Tim

  4. Fertiliser says:

    The above code for Add expire head­ers didn’t post cor­rectly. You can find it at http://www.copypastecode.com/38385/

  5. Admin says:

    Thanks for the reply. Here’s the code you posted.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    
    <ifmodule mod_headers.c>
      # Cache specified files for 6 days
      <filesmatch "\.(ico|flv|jpg|jpeg|png|gif|css|swf)$">
      Header set Cache-Control "max-age=518400, public"
      </filesmatch>
      # Cache HTML files for a couple hours
      <filesmatch "\.(html|htm)$">
      Header set Cache-Control "max-age=7200, private, must-revalidate"
      </filesmatch>
      # Cache PDFs for a day
      <filesmatch "\.(pdf)$">
      Header set Cache-Control "max-age=86400, public"
      </filesmatch>
      # Cache Javascripts for 2.5 days
      <filesmatch "\.(js)$">
      Header set Cache-Control "max-age=216000, private"
      </filesmatch>
    </ifmodule>
  6. I just fin­ished imple­ment­ing this on one of my cus­tomers web­site, and I must tell you, it worked. A bril­liant job done here by you guys. When I was look­ing for the right way to get gzip work­ing with Magento, your list­ing on Google was 3rd but you deserve to be as the first result. A must read for all Magento users. I also liked you on stum­ble upon, good on you guys. Thanks for your kind work.

  7. New York Snow…

    […]The Cor­rect Way To Set Up gzip with Magento – CompRepairGurus[…]…

  8. Tarot Read­ing…

    […]The Cor­rect Way To Set Up gzip with Magento – CompRepairGurus[…]…

Leave a Comment