问题描述:

Using nginx as a reverse proxy I have noted that if a site is pointed at the server but does not actually exist you get served with an existing site on the server rather than a domain cannot be found message or similar.

ie say your config block is listening for portal.test.org the user points there cname to the nginx system but with the domain header of smartportal.test.org

or say the they point a site like portal.test2.org

Could someone direct me on the following

a. How nginx decides which site to return when it does not exist as a virtual host

b. How to catch any domain that are not specified and return a default page that tells users this domain does not exist on this host

Hope someone can help I have tried googling but I think sometimes its knowing the correct terms.

Many thanks

网友答案:

you should use default_server parameter of listen directive and server_name directive.

your questions

  • How nginx decides which site to return when it does not exist as a virtual host

    listen [default_server]

    If the directive has the default_server parameter, then the enclosing server {...} block will be the default server for the address:port pair. This is useful for name-based virtual hosting where you wish to specify the default server block for hostnames that do not match any server_name directives. If there are no directives with the default_server parameter, then the default server will be the first server block in which the address:port pair appears.


    server_name

    This directive performs two actions:

    Compares the Host header of the incoming HTTP request against the server { ... } blocks in the Nginx configuration files and selects the first one that matches. This is how virtual servers are defined. Server names are processed in the following order:

    1.- full, static names

    2.- names with a wildcard at the start of the name — *.example.com

    3.- names with a wildcard at the end of the name — www.example.*

    4.- names with regular expressions

    If there is no match, a server { ... } block in the configuration file will be used based on the following order:

    1.- the server block with a matching listen directive marked as [default|default_server]

    2.- the first server block with a matching listen directive (or implicit listen 80;)

  • How to catch any domain that are not specified and return a default page that tells users this domain does not exist on this host

    server {
      listen 1.2.3.4:80 default_server;
      server_name _ "";
      location / {
        alias /var/www/html/domain-does-not-exists.html; 
       }
    }
    
    server {
      listen 1.2.3.4:80 ;
      server_name portal.test.org;
      location / {
          ... your site ...
       }
    }
    
相关阅读:
Top