The preface

Nginx was designed and developed by LGor Sysoev for Rambler.ru, the second most visited site in Russia. Since its release in 2004, with the power of open source, it has been close to maturity and perfection.

Nginx is rich in features, can be used as HTTP server, can also be used as a reverse proxy server, mail server. Support FastCGI, SSL, Virtual Host, URL Rewrite, Gzip and other functions. It also supports many third party module extensions.

Nginx’s stability, feature set, sample configuration files, and low system resource consumption put it in the lead, with 12.18% of active sites worldwide, or about 22.2 million sites.

If you are not satisfied, you can find such boasting in Baidu Encyclopedia or some books everywhere.

Nginx common functions

Http proxy

Reverse proxy: One of the most commonly used features of web servers, especially reverse proxy. Here I’ll give you two pictures to illustrate the forward proxy and echo proxy. For details, you can refer to the materials.

As a reverse proxy, Nginx provides stable performance and flexible configuration of forwarding functions. Nginx can take different forwarding strategies according to different re matching, such as the end of the image file to go to the file server, dynamic page to go to the Web server, as long as your re write no problem, and the corresponding server solution, you can play as you like. And Nginx to return the results of error page jump, exception judgment, etc. If there is an exception on the server being distributed, it can reforward the request to another server and automatically remove the exception server.

Load balancing

Nginx provides two load balancing policies: built-in policies and extended policies. The built-in policies are polling, weighted polling, and Ip hash. Expansion strategy, on the unconstrained, only you can not think of no he can not do, you can refer to all the load balancing algorithm, to him one by one to find out the implementation.

Understand the implementation of these three load balancing algorithms in the last three figures

The Ip hash algorithm performs hash operations on the Ip addresses requested by clients and then distributes the requests from the same CLIENT Ip address to the same server for processing. In this way, sessions are not shared.

Web caching

Nginx can cache different files for different processing, flexible configuration, and support FastCGI_Cache, mainly used for FastCGI dynamic program cache. In conjunction with ngx_cache_purge, the URL cache content can be added or deleted.

Nginx-related address

Source: trac.nginx.org/nginx/brows…

Website: www.nginx.org/

Nginx configuration file structure

If you have downloaded your installation file, open the nginx.conf file in the conf folder, where the basic configuration of the nginx server is stored, as well as the default configuration.

The comment symbol in nginx.conf is: #

The default nginx configuration file nginx.conf contains the following contents:

“#user nobody; worker_processes 1;

#error_log logs/error.log; #error_log logs/error.log notice; #error_log logs/error.log info;

#pid logs/nginx.pid;

events { worker_connections 1024; }

http { include mime.types; default_type application/octet-stream;

#log_format main '$remote_addr - $remote_user [$time_local] "$request" ' # '$status $body_bytes_sent "$http_referer" ' #  '"$http_user_agent" "$http_x_forwarded_for"'; #access_log logs/access.log main; sendfile on; #tcp_nopush on; #keepalive_timeout 0; keepalive_timeout 65; #gzip on; server { listen 80; server_name localhost; #charset koi8-r; #access_log logs/host.access.log main; location / { root html; index index.html index.htm; } #error_page 404 /404.html; # redirect server error pages to the static page /50x.html # error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } # proxy the PHP scripts to Apache listening on 127.0.0.1:80 # #location ~ \.php${# proxy_pass http://127.0.0.1; #} # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000 # #location ~ \.php${# root HTML; # fastcgi_pass 127.0.0.1:9000; # fastcgi_index index.php; # fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name; # include fastcgi_params; #} # deny access to .htaccess files, if Apache's document root # concurs with nginx's one # #location ~ /\.ht { # deny all; #} } # another virtual host using mix of IP-, name-, and port-based configuration # #server { # listen 8000; # listen somename:8080; # server_name somename alias another.alias; # location / { # root html; # index index.html index.htm; # } #} # HTTPS server # #server { # listen 443 ssl; # server_name localhost; # ssl_certificate cert.pem; # ssl_certificate_key cert.key; # ssl_session_cache shared:SSL:1m; # ssl_session_timeout 5m; # ssl_ciphers HIGH:! aNULL:! MD5; # ssl_prefer_server_ciphers on; # location / { # root html; # index index.html index.htm; # #}}Copy the code

Nginx file structure

. # block events {# block events... } HTTP # HTTP block {... # HTTP global block server #server block {... Location [PATTERN] #location block {... } location [PATTERN] { ... } } server { ... }... # HTTP global block}Copy the code

Global block: configure directives that affect nginx globally. Generally, there are user groups running nginx server, nginx process PID storage path, log storage path, configuration file import, allowed number of worker processes, etc.

2. Events block: The configuration affects the nginx server or network connection to the user. The maximum number of connections per process, which event-driven model to choose to handle connection requests, whether to allow simultaneous acceptance of multiple network connections, enable serialization of multiple network connections, etc.

3, HTTP block: can nest multiple servers, configure proxy, cache, log definition and most functions and third-party module configuration. Such as file import, miME-type definition, log customization, whether to transfer files using SendFile, connection timeout, number of single connection requests, etc.

4, server block: configure the relevant parameters of the virtual host, an HTTP can have multiple servers.

5. Location block: Configure the routing of the request and the processing of various pages.

Below give you a configuration file, as an understanding, but also matched into a test machine I built, to give you an example.

########### Each instruction must end with a semicolon. ################# #user administrator administrators; Configure the user or group. Default is nobody nobody. #worker_processes 2; Pid /nginx/pid/nginx.pid Error_log log/error.log debug; Specify log path, level. This setting can fit into a global, HTTP, server block level to: debug | info | notice | warn | error | crit | alert | emerg events {accept_mutex on; Set network connection serialization to prevent stampedes, default to on multi_accept on; If a process accepts multiple network connections at the same time, the default is off. # event driven model, select | poll | kqueue | epoll | who | / dev/poll | eventport worker_connections 1024; HTTP {include mime.types; Default_type application/octet-stream; The default file type is text/plain #access_log off. Log_format myFormat '$remote_addr - $remote_user [$time_local] $request $status $body_bytes_sent $http_referer $http_user_agent $http_x_forwarded_for'; Access_log log/access.log myFormat; #combined = default value sendFile on; # allow sendFile transfer, default is off, HTTP block, server block, location block sendfile_max_chunk 100k; The number of transfers per call cannot exceed the set value. The default value is 0, that is, no upper limit is set. keepalive_timeout 65; # connection timeout, default is 75s, can be in HTTP, server, location block. Upstream mysvr {server 127.0.0.1:7878 weight=5; Server 192.168.10.121:3333 weight = 10; } error_page 404 https://www.baidu.com; Server {keepalive_requests 120; # Maximum number of single connection requests. listen 4545; Server_name 127.0.0.1; Location ~*^.+${# request url filtering, regular matching, ~ is case sensitive, ~* is case insensitive. #root path; # root directory #index vv.txt; Proxy_pass http://mysvr; Mysvr defines the server list to deny 127.0.0.1; Allow 172.18.5.54; # allowed IP}}}Copy the code

Here is the basic configuration of nginx. Note the following:

1. Common configuration items:

  • Remoteaddr and remote_ADDR and remoteADDR and http_x_forwarded_for are used to record client IP addresses.
  • $remote_user: used to record the client user name;
  • $time_local: records the access time and time zone.
  • $request: used to record the REQUESTED URL and HTTP protocol;
  • $status: Records the request status; Success is 200,
  • $body_bytes_ent: Records the size of the file body content sent to the client;
  • $http_referer: used to record links from that page;
  • $http_user_agent: Records information about the browser on the client.

2, panic phenomenon: when a network connection arrives, multiple sleeping processes are woken up by colleagues, but only one process can get the link, which will affect the system performance.

3. Each instruction must be terminated by a semicolon.