Redirect top level domain in nginx

How to redirect something like “www.example.orgto “www.example.com“, or “longer.subdomain.example.org” to “longer.subdomain.example.com” with a rewrite rule in nginx.conf:

server {
    listen 80;
    server_name "~(?<name>(.*)\.example\.org$";
    rewrite ^(.*) $scheme://$name.example.com$1 permanent;
}

What it does is, store everything that is in front of “.example.org” into the variable ‘name’ and rewrite the URL as ‘name’.example.com. $scheme is an nginx variable that contains the, well, URI scheme, i.e. protocol.

And one that is a little more complex:

server {
    listen 80;
    server_name "~(?<name>((.*)\.(en|ro)|^(en|ro)))\.example\.org$";
    rewrite ^(.*) $scheme://$name.example.com$1 permanent;
}

Translates to “whatever matches (something dot (en or ro)) or starts with (en or ro) in front of ‘example.org’ will be stored into ‘name’ variable”. So basically it redirects any URL that has the language in it to come, but no other kind of subdomain gets redirected.