if ($http_host ~* "^((?!www).*)\.afen\.com$") { set $name $1; rewrite ^ http://www.afen.com/$name$uri; } this can works.