As suggested, I tried using servername in place of the if block:
server_name ~^(.*)\.(.*\..*)$;
set $sub $1;
set $domain $2;
but I get errors like this:
2009/06/16 13:33:20 [emerg] 6443#0: *4 malloc() 18446744073709551612 bytes failed (12: ), client: 89.96.xxx.xxx, server: ~^(.*)\.(.*\..*)$, request: "GET / HTTP/1.1", host: "www.xxxxxxx.eu"
2009/06/16 13:33:24 [emerg] 6443#0: *15 malloc() 18446744073709551612 bytes failed (12: ), client: 89.96.xxx.xxx, server: ~^(.*)\.(.*\..*)$, request: "GET / HTTP/1.1", host: "www.yyyyyyy.it"
while with the previous configuration everything's fine. Rewrites from non-www to www are also perfectly working with your regexp (thanks). I'm using nginx 0.7.51 on Ubuntu Jaunty. I could find some earlier discussions about similar problems, but my russian ain't the best despite some courses I took in the past. :-)