Static content served with nginx

If you followed my last article you now have OFBiz (or Bonsai ERP) running behind nginx. But it isn’t yet taking advantage of nginx goodness. So next I am going to show you how to take the load of serving static content away from OFBiz, and give it to nginx instead.

How will it work?

Most of OFBiz’s static content is served via the images webapp. We will configure nginx to look there for static files such as jpg, png, gif, css, and js, and serve them directly if found. If not found, nginx should ask OFBiz to supply the right response to the request.

How to do it?

First set nginx’s root to point to the images webapp directory. If you have OFBiz or Bonsai ERP installed in /opt/bonsaierp, you would ensure the following line was inside nginx’s server sections for both SSL and non-SSL servers.

root /opt/bonsaierp/framework/images/webapp/images;

This tells nginx to look in this directory for files if it hasn’t been told otherwise.

Next find the location section we added last time to the nginx configuration, and change the / to @bonsaierp so it looks like this:

location @bonsaierp {
proxy_pass http://127.0.0.1:8080;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded_For $proxy_add_x_forwarded_for;
}

Of course, the 8080 will be 8443 for the SSL version.

This location does nothing on its own. Other location sections we create below will refer to this one. It’s an easy way to keep the OFBiz interaction commands in one spot.

Next add a location section specifically aimed at the static files:

location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
try_files $uri @bonsaierp;
expires 7d;
}

The expires line is optional, but nice to have. The expires tells the user’s browser that it can keep a copy of this file for up to 7 days before needing to fetch a new copy. This speeds page loads for repeat visitors.

The try_files tells nginx to first look in the root directory, which we specified earlier, for the requested file. If it isn’t found, then ask OFBiz for it using the instructions in the @bonsaierp location.

Finally add a new location that will be used for requests that don’t match the js,css,png,etc location.

location / {
try_files $uri @bonsaierp;
}

What’s next?

We are now getting value out of having installed nginx. As most requests to a web server are typically for static files, we’ve just greatly reduced the load on our web server, and can serve the same number of visitors faster and with much lower memory usage.

But there are a few more niceties we might want to add. I’ll mention some of those in the next article, and show a full nginx server section configuration.