I recently set up a new server to host website for my clients. I took the opportunity to re-think how I have been serving sites and optimize the whole software stack for better performance. Rather than the usual LAMP (Linux/Apache/MySQL/PHP) stack, I decided to go with LEMP, switching Apache out for Nginx. Although most common PHP applications recommend Apache, they will actually run faster on Nginx. Usually all you just need to do is translate the .htaccess file rules into Nginx’s configuration file.
My first order of business once the new server was set up was to get WordPress running and to optimize its performance. The first few sites that would be going on the new hardware were using WordPress so although I will be going through a similar process for Expression Engine soon, WordPress was my test-case.
I always run the W3 Total Cache plugin with my WordPress installations. By storing copies of each rendered page to disk (as well as many other optimizations), W3TC dramatically decreases the load on the server under heavy traffic. This is particularly the case with the Nginx configuration I am about to show you, which lets most requests be handled by Nginx alone. Nginx was designed first and foremost as a reverse proxy, so it serves static files almost instantly and with minimal processor or memory usage. There are a number of sample configurations around the web for running WordPress with W3TC on Nginx, but none of them quite did it for me. For one thing, they all rely heavily on
if statements, which are evil. So here is my take on it….
First, you need to install W3 Total Cache. This will add a “Performance” section at the bottom of the left-hand menu in your control panel. W3 Total Cache has many, many options and I am not going to explain them all here. To begin with, though, select the checkboxes to enable “Page Cache”, “Minify”, “Object Cache”, and “Database Cache”. The Page Cache method should be set to “Disk Enhanced” and all the others to “Disk” or “Opcode” if available.
The important part of this post! You need to add the following configuration to your
nginx.conf file (or to a separate file in
/etc/nginx/sites-available/, which is the recommended way of doing things). I am assuming you already have Nginx running with PHP-FPM. If not, there are plenty of tutorials available around the web, depending on your Linux distro.
- I had to comment out the
PATH_INFOline in my
fastcgi_paramsin order for images urls in minified CSS files to be correct. Doing so doesn’t seem to have had any negative effects.
- Some of this code would be better off in your main
httpblock, rather than the
serverblock. I have arranged it this way for simplicity and clarity. Read more about how you should structure your configuration.
- I’m not an Nginx configuration expert, so there may be ways to improve this code. Please share anything you see and I will update the post.