Gzip Encoding


On PHP pages that I get control over, one of the first things I do is add Gzip encoding. This compresses the text on the page for browsers that can handle it, and really reduces network traffic, speeding up page load/download times on dial-up (well, and broadband) connections significantly.

On PHP this is really easy, its just one line of code at the top of the page:

ob_start('ob_gzhandler');

But until now, I had trouble finding out how to do this for .NET sites. All I could find was that you can enable it server-wide on IIS but now I found this handy bit of code that can go at the top of your .NET pages.

string AcceptEncoding = HttpContext.Current.Request.Headers["Accept-Encoding"];
if (!string.IsNullOrEmpty(AcceptEncoding) && AcceptEncoding.Contains("gzip"))
{
    HttpContext.Current.Response.AppendHeader("Content-Encoding", "gzip");
    HttpContext.Current.Response.AppendHeader("Vary", "Content-Encoding");
    HttpContext.Current.Response.Filter = new System.IO.Compression.GZipStream(HttpContext.Current.Response.Filter, System.IO.Compression.CompressionMode.Compress);
}

And that’s it. Tasty Gzip encoding for all. The next step is testing it, which I use the mod_gzip_test site for. You can see an example of the changes we made to gameplayer.co.nz (a .net site) here

  1. #1 by Jared on 2010-02-21 - 4:20 pm

    Hey Eion, Great site. Thanks for this post! Been doing PHP for 10 years and never used GZip! Great idea. Jared (ChCh)

Comments are closed.