Aspyct.org

Setting up HTTP cache and gzip with nginx

| Comments

Spending a little time on the PageSpeed utility from Google made me realize that I could probably finetune my webserver to serve pages even faster :) The two main tracks were 1) enable gzip compression and 2) use HTTP caching.

I won’t delve into details here, but only give you the solution. You will find the source links at the end of this post.

First, let’s enable the gzip compression at the server level. Write the following in your nginx.conf file:

1
2
3
4
5
6
7
8
gzip  on;
gzip_http_version 1.1;
gzip_vary on;
gzip_comp_level 6;
gzip_proxied any;
gzip_types text/plain text/html text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript application/javascript text/x-js;
gzip_buffers 16 8k;
gzip_disable "MSIE [1-6]\.(?!.*SV1)";

Way to go, reload nginx config and refresh the pagespeed analytics. Hooray, we just won 8 points on the scale! (at least I did ;) And now for the HTTP caching (put this in your sites-available/ config file):

1
2
3
4
5
6
7
8
9
location ~* \.html$ {
  expires -1;
}

location ~* \.(css|js|gif|jpe?g|png)$ {
  expires 168h;
  add_header Pragma public;
  add_header Cache-Control "public, must-revalidate, proxy-revalidate";
}

You can see that I disabled expire on the .html files, otherwise you could be stuck with this version of aspyct.org until the end of time… However, I put one week (7 * 24h) for css, js and images. They don’t change often, so this could be bigger, but this lets me a chance to change it anyway.

So, what is your trick to speed up your nginx powered website?

Sources:

Comments