It's a bit late to answer, in the end with Ivan's help I made this regular expression. I defined a site with it if a request falls on this site, nginx will remove the subdomain.
if ($host ~ "^[^.]+\.(?<domain>[^.]+\..+)$") {
rewrite ^ $scheme://$domain$request_uri permanent;
}