Apply NGinx redirects only to main domain excluding subdomains

I have a setup of a PHP application listening in several hosts, for example:

maindomain.com a.maindomain.com b.maindomain.com

Some routes in maindomain.com need to be redirected. For that, I configured this redirection time ago:

rewrite ^/myroute/(.*)$ http://$server_name/new-myroute/$1 permanent;

Which makes all requests to maindomain.com/myroute/ redirect to maindomain.com/new-myroute.

The thing is that this redirects also apply to the rest of the subdomains, making a.maindomain.com/myroute redirect to maindomain.com/new-myroute.

I would like to exclude these subdomains from applying that redirection, leaving routes type a.maindomain.com/myroute untouched.

I've tried with different rewrites, like

rewrite ^https://maindomain.com/myroute/(.*)$ http://$server_name/new-myroute/$1 permanent;

rewrite ^maindomain.com/myroute/(.*)$ http://$server_name/new-myroute/$1 permanent;

rewrite maindomain.com/myroute/(.*)$ http://$server_name/new-myroute/$1 permanent;

But none of them work.

Any ideas about how to apply the redirect only to the main domain? Thanks.

Edit: the server name has a wildcard, listening to all possible subdomains that could exist:

server_name maindomain.com *.maindomain.com;

Either use a separate server block or use an if condition

if ($host = "example.com") {
    rewrite ^/myroute/(.*)$ http://$server_name/new-myroute/$1 permanent;
}