CakePHP Performance: Rewrite plugin assets in Nginx

This post dated from 2011. Today CakePHP has a better (and faster) dispatch handler for assets. However, for the best performance, this article is still very useful.

Lately I’m playing with the Nginx webserver. Nginx is a free, open-source, high-performance HTTP server hosting 7.5% of all webservers on the internet (that’s 20.5M webservers).

CakePHP plugin assets are served through PHP, which makes it obviously slower than serving it without invoking PHP. I found a little solution that speeds up every plugin asset by ~ 60ms. So when you have lots of images, css and javascript files in your plugins, you can speed up your page load time by several seconds!

One of the great benefits is the freedom and flexibility of the configuration files, so I played a bit with the ‘try_files functionality‘ which results in amazing performance improvements.

1
2
3
4
5
6
7
8
# Serve CakePHP plugin assets directly
location ~ /(.+)/(img|css|js|files)/(.*) {
access_log off;
expires 10d;
add_header Cache-Control public;
try_files $uri $uri/ /../plugins/$1/webroot/$2/$3 /../../plugins/$1/webroot/$2/$3 /index.php?url=$uri;
}

You can find (and fork) my full configuration example in my github repo:

https://github.com/Lennaert/Lennaerts-Snippets

For a full Nginx / PHP / CakePHP setup I could truly recommend the blog post of Kevin van Zonneveld and Chris Hartjes, I learned a lot from them!