Nginx configuration file explained

nginx

I have a few questions about this configuration file "default" in /etc/nginx/sites-enabled. It is shown below.

server 
{
  root /usr/share/nginx/www;
  index index.html index.htm;

# Make site accessible from http://localhost/
server_name localhost;

location / {
    proxy_pass http://127.0.0.1:8080;
}

location /doc {
    root /usr/share;
    autoindex on;
    allow 127.0.0.1;
    deny all;
}

location /images {
    root /usr/share;
    autoindex off;
   }
}
  1. There is no "Listen" directive, how does it know to default to 80
  2. The server_name is localhost, how does another domain work?
  3. Why is the location directive embedded in the server directive? Does that mean these locations ONLY apply to this server?
  4. None of my configs have listen 80 default_server; how does nginx then pick what configuration to use?

Best Answer

Just a quick disclaimer: the sites-enabled/sites-available layout isn't something from nginx itself, but rather from you package maintainer. By default nginx provides single nginx.conf sample config which is more obvious than multiple files joined via include as found in some linux packages. Here are answers in order:

There is no "Listen" directive, how does it know to default to 80

This is because nginx listens on port 80 (or 8000 if run as non-root) by default, see http://nginx.org/r/listen.

The server_name is localhost, how does another domain work?

By default nginx uses first server in a config as default one (and uses it to process domains not matched against other servers server_name directives). As long as sites-enabled/default is the only server in your config - it will actually work as default one. If you'll add more servers - it will likely break. See detailed explanation at http://nginx.org/en/docs/http/request_processing.html.

Why is the location directive embedded in the server directive? Does that mean these locations ONLY apply to this server?

Yes, location directives may be specified only within some certain server and only apply to requests matched this server.

None of my configs have listen 80 default_server; how does nginx then pick what configuration to use?

First server block found in config will be the default. As include with wildcards doesn't impose any ordering, it will likely be some random server block.