Monday, April 15, 2013

How to compress a website with gzip

Gzip compression is one of the way to optimize site performance. A client browser sends a header request of Accept-encoding: gzip, deflate. Then server knows that his client is gzip enabled. It compresses it's contents and sends back Content-encoding: gzip, deflate.

    There are several ways to gzip compress a website.
  • Using .htaccess: We can enable gzip compression with .htaccess file. For that we need to enable mod_deflate or mod_gzip. It's pretty simple to work with mod_deflate. To enable it, please uncomment the load module line in httpd.conf file.
    LoadModule deflate_module modules/mod_deflate.so
    

    Now restart apache. You are all set to go with deflate module.
    Please open your .htaccess file and add the below code block:
    
    # compress text, html, javascript, css, xml:
    AddOutputFilterByType DEFLATE text/plain
    AddOutputFilterByType DEFLATE text/html
    AddOutputFilterByType DEFLATE text/xml
    AddOutputFilterByType DEFLATE text/css
    AddOutputFilterByType DEFLATE application/xml
    AddOutputFilterByType DEFLATE application/xhtml+xml
    AddOutputFilterByType DEFLATE application/rss+xml
    AddOutputFilterByType DEFLATE application/javascript
    AddOutputFilterByType DEFLATE application/x-javascript
    
    # remove browser bugs
    BrowserMatch ^Mozilla/4 gzip-only-text/html
    BrowserMatch ^Mozilla/4\.0[678] no-gzip
    BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
    Header append Vary User-Agent 
    
    

    First of we set the file content types which will be process with deflate module to compress. we compress text, html, javascript, css, xml and css files.
    Then, we add some exceptions. like for Mozila version 4, we only compress text files. And also for IE, we will not gzip our contents. Because there is some bug with compression in those user agents.
  • If we don't have mod_deflate enabled or we don't have proper permission to write .htaccess files, then we can compress files using php ob_gzhandler function.

    
    

    We check the "Accept-encoding" header and return a gzipped version of the file; otherwise the regular version.


See the book OpenCart 1.4 Template Design Cookbook.
See the book Joomla Mobile Development Beginners Guide




List of my works:

Opencart Extensions:

  1. Product Based Quantity Wise Shipping: Find it here.
  2. OpenSSLCOMMERZ: integrate SSLCOMMERZ with opencart: Find it here.
  3. Fine Search v.1.0 - Improves Opencart search feature to find relevant: Find it here.
  4. Opensweetcaptcha - An easy way to generate attractive captcha for your system!: Find it here.
  5. Custom Field Product - add unlimited custom fields to the product form: Find it here.
  6. Formcaptcha - add captcha on the register page: Find it here.

My Books:

  1. OpenCart 1.4 Template Design Cookbook.
  2. Joomla Mobile Development Beginners Guide

No comments: