playing with nginx

Virtually all of my Drupals are hosted on a single server, running Apache with mod_php5. Apache is by no means light-weight, so the server is starting to creak a bit under the combined load of all these sites.

I've been meaning to have a go at configuring nginx with php5 in fastcgi mode, to check the difference this would make on system load.

The tricky thing is that I run all my Drupals from a single code base and use Apache's mod_vhost to run all these sites from a single configuration file. Basically mod_vhost will service a web site from a specific directory if that directory exists in a specific location.

Because of this, none of the Drupals use the /files directory either, but store all their data in sites/sitename/files. Some rewrite rules then make sure that a request for an image or css in /files gets redirected to the correct location.

Of course I wouldn't want to switch back to a per-host configuration file, so I needed to find out how to make nginx do the same thing. A spot of googling found me the right configuration directives. I've included the basics below.

server {
  listen 80;

  location / {
    # Define a virtual document root, based on the host name.
    root /srv/www/$host/html;
    index index.php;
    # Strip www. from the host name and redirect. 
    # This means less symlinks are needed for sites/* and search
    # engines only index foo.com, not www.foo.com as well.
    if ($host ~* "^www\.(.*)$") {
      set "$domain" "$1";
      rewrite (.*) http://$domain$uri permanent;
    }
    # Make index.php handle urls that don't exist on disk.
    if (!-e $request_filename) {
      rewrite ^/(.*)$ /index.php?q=$1 last;
      break;
    }
  }
  # Rewrite /files to be served from the per-site files dir.
  location /files {
    rewrite ^/files/(.*)$ /sites/$host/files/$1 last;
  }
}

Nginx current runs on port 81, so you can have a go of it via http://cafuego.net:81/. Nginx is now live on port 80. I'm not sure if it would be possible or more efficient to simply stick a different root directive in the /files location, rather than rewriting the uri.

The rest of the nginx and fastcgi configuration, including init scripts, can be found at http://drupal.org/node/110224.

Comments

Add new comment