fLOyd
fLOyd

Reputation: 505

Why could I access a nginx server even there is only virtual host of localhost in config?

I have a host installing nginx with default configuration. It's weird for me that even in the default nginx.conf there is only a virtual server with server_name localhost, but still I could access the nginx welcome page from my laptop.

I am pretty sure the configuration file is used by nginx as when I changed the root of location /, it takes effect after restarting the service.

Any suggestions or any ideas on how I could deep diver on this?

Upvotes: 0

Views: 1249

Answers (1)

Shawn C.
Shawn C.

Reputation: 6841

Nginx default config is something starting like:

server {
    listen       80;
    server_name  localhost;
    ...
}

Listens tells Nginx the hostname and the TCP port where it should listen for HTTP connections. FYI 'listen 80;' is equivalent to 'listen *:80;'

server_name lets you domainname-based virtual hosting. As you assumed. But you only have one server block. So the listen is taking control. Basically it sees a request on port 80 and goes well as I don't have a better selection I will use this server block. Now if you add more server blocks on port 80 then Nginx will start using server name(s) as a means to figure out which to use.

You can add a server block like:

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

Which will became the default server if nothing else matches.

Hope that helps.

Upvotes: 2

Related Questions