Here's a variant on Brenton Alker's anser, using the $server_name
variable to reuse the value of the server_name
directive.
server_name primary.tld secondary.tld;
if ($host != $server_name) {
rewrite ^ $scheme://$server_name permanent;
}
Or, to keep any query parameters:
server_name primary.tld secondary.tld;
if ($host != $server_name) {
rewrite ^/(.*) $scheme://$server_name/$1 permanent;
}
Here, $server_name
refers to primary server name, which is the first name in the server_name
directive, while $host
refers to the hostname given in the HTTP request.
Note that the if
statement in nginx configuration does not always do what you would expect and its use is discouraged by some. See also https://www.nginx.com/resources/wiki/start/topics/depth/ifisevil/