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

1. Http proxy, reverse proxy: as one of the most commonly used functions 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.

2. 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.

3. 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.

4, 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 annotation bit # in nginx.conf

Nginx file structure, this entry to the students, you can see two eyes.

The default config

#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

.# global block

events {         # events block. } http# HTTP block{...# HTTP global block
    server        # server block{...# server global block
        location [PATTERN]   # the location of 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; # Number of processes allowed to be generated. Default is 1
#pid /nginx/pid/nginx.pid; # specify the location where nginx run files are stored
error_log log/error.log debug;  Specify log path, level. , this setting can fit into a global, HTTP server block, level as: debug | info | notice | warn | error | crit | alert | emerg
events {
    accept_mutex on;   Set network connection serialization to prevent stampedes. Default is on
    multi_accept on;  Set whether a process accepts multiple network connections at the same time. Default: off
    #use epoll; # event driven model, select | poll | kqueue | epoll | who | / dev/poll | eventport
    worker_connections  1024;    # Maximum number of connections. Default is 512
}
http {
    include       mime.types;   File extension and file type mapping table
    default_type  application/octet-stream; The default file type is text/plain
    #access_log off; Cancel service log
    log_format myFormat '$remote_ADDR - $remote_user [$time_local] $request $status $body_bytes_SENT $http_referer $http_user_agent $http_x_forwarded_for'; # Custom format
    access_log log/access.log myFormat;  #combined is the default value for logging format
    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; 3333 backup server 192.168.10.121:;# hot standby
    }
    error_page 404 https://www.baidu.com; # error page
    server {
        keepalive_requests 120; # Maximum number of single connection requests.
        listen       4545;   # monitor portServer_name 127.0.0.1;# monitor address
        location  ~*^.+$ {       # request url filtering, regular matching, ~ is case sensitive, ~* is case insensitive.
           #root path; # the root directory
           #index vv.txt; Set the default page
           proxy_pass  http://mysvr;  Request redirected to mysvr defined server listDeny 127.0.0.1;Rejected IPAllow 172.18.5.54;# Allowed IP}}}Copy the code

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

1. Common configuration items:

  • 1.$remote_addr$http_x_forwarded_forTo record the IP address of the client;
  • 2.$remote_user: Used to record the client user name;
  • 3.$time_local: Records the access time and time zone.
  • 4.$request: Used to record the REQUEST URL and HTTP protocol;
  • 5.$status: Records the request status. Success is 200;
  • 6.$body_bytes_s ent: Records the size of the file body sent to the client.
  • 7.$http_referer: used to record visits from that page link;
  • 8.$http_user_agent: Records information about the client browser.

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.

Xiaobian recommendation:

As a coder, I have collected many excellent websites at home and abroad, including online tools, online operation, free interface, online resources, online learning, technical forum, technical blog and so on, to meet the daily needs of ordinary programmers.

Address: nav.imaring.com/

Address 2: www.code-elf.cn/

Original address:www.cnblogs.com/knowledgese…