My code doesn't work with second level tld's like domain.co.uk
Here is my conf:
# add www.
if ($host ~ ^(?!www)) {
rewrite ^/(.*)$ http://www.$host/$1 permanent;
}
# remove subdomain
if ($host ~ "^www\.(.*)\.(.*\.([a-z]{2,4}|[a-z]{2}\.[a-z]{2}))") {
set $host_without_sub $2;
rewrite ^/(.*)$ http://www.$host_without_sub/$1 permanent;
}