Oct 22, 2013

f Comment

Nginx: How to Map Any Subdomain Name to a Specific Domain Name?

Amazon If you use Nginx web server you may be wondering how to configure it to map any name to a specific name. For example I would like my server to be able to serve pages from two domain names:

www.chtoen.com
s.chtoen.com

And I'd like any other domain names (e.g. abc.chtoen.com, 123.chtoen.com) to be 301 permanently redirected to www.chtoen.com. How do I achieve this goal by adjusting the Nginx configuration file?

Nobody on Google seems to know what * in *.chtoen.com is called. For example what do we call www in www.chtoen.com? Let's call it a subdomain in the scope of this article.

Solution

It turns out the solution is simple. Simply use wildcard character (*) in server_name directive to match any text of any length. Then redirect them to www.chtoen.com. The following is an example.
server{
  listen 80;
  server_name chtoen.com *.chtoen.com;
  rewrite ^/(.*) http://www.chtoen.com/$1 permanent;
}

server{
  listen 80;
  server_name www.chtoen.com s.chtoen.com;
  root /home/www/chtoen;
  # .. other directives to define how to handle these webpages ..
}
Now when a client requests chtoen.com, a.chtoen.com, abc123.chtoen.com, etc., it will be 301 redirected to www.chtoen.com.

To see why this configuration works read on.

Why does this configuration map any subdomain name to www?

You may wonder why this configuration works because when an HTTP request for www.chtoen.com comes in shouldn't Nginx use the server block containing server_name chtoen.com *.chtoen.com to handle the request? Then you would have an infinite loop redirecting the client to www.chtoen.com infinitely.

The answer is when searching for a virtual server by name, if name matches more than one of the specified variants, e.g. both wildcard name and regular expression match, the first matching variant will be chosen, in the following order of precedence:

exact name
longest wildcard name starting with an asterisk, e.g. "*.example.org"
longest wildcard name ending with an asterisk, e.g. "mail.*"
first matching regular expression (in order of appearance in a configuration file)

Nginx will always use the above order of precedence to match a virtual server. When an HTTP request for www.chtoen.com comes in Nginx would match it with the exact name which is defined by the second server block in the example configuration above.

Questions? Let me know!

To see if your version of Nginx supports the aforementioned directives please go to http://nginx.org/en/docs/http/server_names.html. Wildcard form *.example.org has been supported since 0.1.13.
Please leave a comment here!
One Minute Information - by Michael Wen
ADVERTISING WITH US - Direct your advertising requests to Michael