Follow this Blog!

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:

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

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


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 The following is an example.
  listen 80;
  server_name *;
  rewrite ^/(.*)$1 permanent;

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

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 comes in shouldn't Nginx use the server block containing server_name * to handle the request? Then you would have an infinite loop redirecting the client to 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. "*"
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 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 Wildcard form * has been supported since 0.1.13.
Please leave a comment here!
One Minute Information - by Michael Wen
Find Michael on Google or Facebook
ADVERTISING WITH US - Direct your advertising requests to Michael