As @Ricoxor answered, you could use a rewrite to get the correct functionality; however, this is listed as an examplary pitfall in the Nginx Pitfalls documentation.
The correct way to do this would be to write multiple server directives as shown by the documentation:
server {
server_name www.domain.com;
return 301 $scheme://domain.com$request_uri;
}
server {
server_name domain.com;
[...]
}
The reason this is more 'correct' is described at the page linked:
There are actually three problems here. The first being if directives. That's what we care about now. Why is this bad? Did you read If is Evil? With if directives Nginx is forced to evaluate every request for all domains. Evaluating every request against if directives is extremely inefficient. Avoid using if directives and use two server directives as shown.