How to configure nginx to auto redirect to the main hostname?

sorin picture sorin · May 10, 2012 · Viewed 32.7k times · Source

Each nginx config can act for a wide range of domains but I want to auto-redirect requests to the first domain name (the official one).

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

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

Answer

kolbyjack picture kolbyjack · May 10, 2012

This is pretty much the same thing as the GOOD example for http://wiki.nginx.org/Pitfalls#Server_Name. That is, you should 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
}