Analysis of Implementation Process of nginx Handling http Request

  • 2021-09-25 00:08:00
  • OfStack

nginx first decides which server {} block in the configuration file to process, assuming the following server {} configuration


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

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

nginx determines which server {} to use based on the value in the Host field in the incoming http request header.

If there is no Host field in the request header, or the value in the Host field does not match {server_name} in server {} in the Nginx configuration file, the first server {} is used to process the request.

If the value in the Host field in the request header matches the {server_name} in an server {} in the Nginx configuration file, then the server {} is used to process the request.

You can use curl tool to do experiments conveniently, curl can set the request header of http request, so you can set Host field arbitrarily and use "-H" to set it. 10.210. 65.73 below is the IP address of the machine where nginx is installed.

So with the following command, after sending an http request, nginx will use server {server_name aaa} to process the request.

curl.exe -H "Host: aaa" 10.210.65.73

Very important conclusion: server_name corresponds to the value of Host field in http request header. With the above theoretical support, reverse proxy and load balancing can be easily set:

When the Host field in the incoming http request header is aaa, storage. test is processed.

When the Host field in the incoming http request header is bbb, tracker. test is processed.


  # Load balancing configuration, IP For 129 The machine configuration is high, so give him the number of 27 Is to make it multiprocess 
  upstream storage.test {
   server 10.210.65.129:80 weight=27;
   server 10.210.65.130:80 weight=1;
  }

  # Load balancing configuration 
  upstream tracker.test {
   server 10.210.65.52:80 weight=7;
   server 10.210.65.53:80 weight=2;
  }

  # Storage of files 
  server {
    listen    80;
    server_name aaa;
    location / {
      #http::// The following content is defined by oneself , Corresponding to the top upstream The name of 
      proxy_pass http://storage.test;
    }
  }

  # File server tracker
  server {
    listen    80;
    server_name bbb;

    location / {
      #http::// The following content is defined by itself, corresponding to the above upstream The name of 
      proxy_pass http://tracker.test;
    }

  }

Whose port is listen listening on in server {}?

Listening is on the port of the process (mostly the browser) that sent the http request (port 80 if it is an http request), not the port of the nginx server's own process.

nginx determines which server {} to use to process http requests based on the value in the Host field in the http request header and the port of the process (mostly the browser) that sent the http request.


Related articles: