nginx-virtual-server

Overview

In nginx, a virtual server is defined by a server block with listen directive inside it, something like this.

1
2
3
4
server {
listen 1.1.1.1:8000;
server_name a.b.com;
}

Each virtual server has a unique context, for each request, we first need to know who should be right server that serves the request, this is determined by comparing Host header value or SNI with server_name configured with each virtual server, if none matches, use default virtual server, default virtual server is the one with default keyword in listen directive, if no default configured, the first one in the config(nginx.conf) for that ip:port.

As there could be multiple virtual servers(with different names) listen on same ip:port, nginx builds a hash for the server names for quick searching the matched one, input: Host(SNI): output: server block ctx, the next section I will show how virtual server is parsed and management in runtime.

As epoll supports metadata for fd, nginx stores combined context to VIP fd, hence when a new connection comes, we already know that context, from that context get the proper vip by comparing Host header or SNI or use default.

1
2
3
4
5
/* same ip:port only has one ngx_listening_t(combined context) */
ngx_listening_t {
/* virtual servers ctx listen array of ngx_http_in_addr_t, for example */
void *servers;
}

virtual server organize

virtual server layout