nginx and asterisk server_name?

11,879

Solution 1

As @Valery Viktorovsky's answer says, you can't use a * for server_name. You can designate a server block as the "default" to receive all requests which don't match any others. See this post for an explanation. It would look like this:

server {
    listen 80 default_server;
    server_name wontmatch.com; # but it doesn't matter
}

See the docs for server_name for more.

Solution 2

You can't use * for server_name. From the documentation:

A wildcard name may contain an asterisk only on the name’s start or end, and only on a dot border.

However, you can use a regular expression:

server {
    server_name   ~^(www\.)?(.+)$;

    location / {
        root   /sites/$2;
    }
}

Solution 3

FYI, for those like me who were looking for something a little different, the following configuration will listen and respond to all port 80 request whether you use IP or URL (AKA everything):

server {
    listen 80 default_server;
    server_name _;
...
}

Taken from: http://nginx.org/en/docs/http/server_names.html

In catch-all server examples the strange name “_” can be seen:

server { listen 80 default_server; server_name _; return 444; } There is nothing special about this name,...

You will get errors on sudo service nginx restart or ... start while /etc/nginx/sites-enabled/default symbolic link is still active since it uses the same matching pattern. Simply remove that link and everything should work.

Solution 4

Just a quick update.. according to the docs the wildcards do work now: http://nginx.org/en/docs/http/server_names.html

Share:
11,879
Ahmed
Author by

Ahmed

Updated on June 11, 2022

Comments

  • Ahmed
    Ahmed almost 2 years

    Is there a way to proxy all traffic to a certain server unless the domain is something different?

    Basically a * for the server_name property?

    server {
      listen 80;
      server_name foo.com
    }
    
    server {
      listen 80;
      server_name *
    }
    

    Or, is there a way to set a "default" server, and then it would use it if none of the other specific server configs match?

  • CMCDragonkai
    CMCDragonkai almost 10 years
    Why is it $2 and not $1?
  • sanityinc
    sanityinc over 9 years
    That appears to be a typo: it should be $1.
  • Robbo
    Robbo about 9 years
    $2 is correct, it is the second group that you want
  • Oliver Dixon
    Oliver Dixon about 7 years
    How would I achieve this for a specific domain since I have other domains on the same server?