Adding rewrite for non-www to www

The easiest way to add an Nginx rewrite to redirect your traffic from non-www to www is to add the following Nginx code snippet to your domain's ___general/example.com.conf file.

set $redirect "0";
if ($host ~* "^(.+)\.example\.com$") { set $cursubdomain $1; }
if ($host != www.example.com)        { set $redirect "go"; }
if ($cursubdomain = "")              { set $redirect "go${redirect}"; }
if (!-d $root_dir/$cursubdomain)     { set $redirect "go${redirect}"; }
if ($request_method = PURGE)         { set $redirect "0"; }
if ($redirect = "gogo") {
  rewrite ^(.*)$ $my_http://www.example.com$1 permanent;
}

! Be sure to change example.com to suit your own domain name