Experimenting with nginx

Seeing as how nginx is gaining popularity, partially due to it's performance on small virtual machines, aka virtual private servers, I decided to move my some of my personal sites to an nginx host from my current apache2 solution.

While I was in the process of doing this, I thought it would be handy to be able to create a new subdomain on the fly. There is already a wildcard configured in DNS, so now I just needed a wildcard setup in nginx.

This configuration checks for the existence of the directory named for the subdomain, if it doesn't exist, it redirects to www.domain.tld.

In theory, if all domains were in a standard base directory, I could have one configuration file that would route any website to the correct location. Maybe I'll experiment with that later.

And yes, I know that this kind of thing can be done with apache2 as well.

server {
   index index.html index.htm index.php;
   set $basepath "/home/username/";
   server_name ~^(?<sub>.+?)\.domain\.tld$;

   set $root $basepath/$sub.domain.tld;

   if ( !-d $root ) {
      rewrite ^ $scheme://www.domain.tld$uri redirect;

   root $root;

   location / {
      # First attempt to serve request as file, then
      # as directory, then fall back to displaying a 404.
      try_files $uri $uri/ /index.html;
   # pass the PHP scripts to php-fpm
   location ~ \.php$ {
      fastcgi_split_path_info ^(.+\.php)(/.+)$;
      fastcgi_pass unix:/var/run/php5-fpm.sock;
      fastcgi_index index.php;
      include fastcgi_params;

   # deny access to .htaccess files, if Apache's document root
   # concurs with nginx's one
   location ~ /\.ht {
   deny all;