How to configure nginx to automatically redirect to primary host name?

Each nginx configuration can act for a wide range of domains, but I want to automatically redirect requests to the first domain name (official).

server { server_name a.example.com b.example.com; } 

I want if someone enters b.example.com/some , go directly to a.example.com/some

+7
source share
2 answers

This is almost the same as the GOOD example for http://wiki.nginx.org/Pitfalls#Server_Name . That is, you must use two servers:

 server { server_name b.example.com; return 301 $scheme://a.example.com$request_uri; # For pre-0.8.42 installations: # rewrite ^ $scheme://a.example.com$request_uri? permanent; } server { server_name a.example.com; # Do stuff } 
+9
source

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.

+1
source

All Articles