To do this in one server block, you can use the if variable and $server_name :
server_name primary.tld secondary.tld; if ($host != $server_name) { rewrite ^ $scheme://$server_name permanent; }
Or, to save any query parameters:
server_name primary.tld secondary.tld; if ($host != $server_name) { rewrite ^/(.*) $scheme://$server_name/$1 permanent; }
Here $server_name refers to the name of the primary server, which is the first name in the server_name directive, and $host refers to the host name specified in the HTTP request.
Please note that the if in the nginx configuration does not always do what you expect, and its use is not recommended. See also https://www.nginx.com/resources/wiki/start/topics/depth/ifisevil/
This answer was inspired by this answer to another question that takes a similar approach.
Matthijs kooijman
source share