Have you fallen prey to misconfiguring Nginx?

08 Aug 2012 - sysadmin ubuntu

Ever googled for Nginx configuration? For example, how to redirect http://www.example.com to http://example.com? I have, and guess what, most of the top results are wrong or inefficient. All of these are documented in a Pitfalls page on the Nginx wiki. I’m just going to point out the parts of my config I’ve optimized recently with great help from the Nginx wiki.

Nginx Configuration - The top Google results are wrong or inefficient!

Redirect from www to non-www

Nginx wiki recommends using return, but the version in Ubuntu 10.04 doesn’t seem to support it, so I use this:

rewrite ^ //nigelb.me$request_uri? permanent;

Static files

Set the Expires and Cache-Control headers with the expires header. Another thing I do is turn off access log for static files.

location ~ ^/(img|js|css)/ {
        expires 30d;
        access_log off;
}

Running PHP with Nginx

Most PHP applications only have an index.php file that needs to be executed, everything else is usually an include.

location ~ index.php$ {
        include fastcgi_params;
        fastcgi_pass    unix:/tmp/php.socket;
}

Remember to place your root directive outside any location block. Then, you can add another route for static files, just so that Nginx can serve them instead of that request going to PHP.

location ^~ /pub/ {
}

By no means are these meant to be authoritative, and newer versions of Nginx lets you use try_files instead of some of what I’ve done.

TL;DR: Use the Nginx Wiki. RTFM.

Update: Lyz pointed out that the default config file that come with the CentOS packages on the Nginx website put root inside the location block instead of outside. She’s just helped me verify that and I verified the same problem with the Ubuntu packages from the Nginx website.