Nginx (1.20.0) (operating system CentOS-8.4.2105-x86_64) (under continuous update...)

Nginx (1.20.0) (operating system CentOS-8.4.2105-x86_64)

purpose

  • Forward proxy: the client accesses the WAN service through the proxy server in the LAN. Shield the client from the server.
  • Reverse proxy: the client accesses the specified service, and the service is forwarded to the target server in the LAN through the proxy server. Shield the server from the client.
    • Dynamic and static separation: dynamic resources and static resources are served separately.
    • Load balancing: the same request is forwarded to one of different services according to rules.




install

express setup

  • Install: yum install nginx
  • Set startup to start Nginx service: systemctl enable nginx
  • Start Nginx service: systemctl start nginx
  • To verify that the service is running, check its status: systemctl status nginx

custom installation

  • Installation dependency
    • express setup
      • gcc__
        • Purpose: compile source code
        • Install: yum -y install gcc-c++
      • pcre,pcre-devel
        • Purpose: PCRE(Perl Compatible Regular Expressions) is a Perl library, including Perl compatible regular expression library. The http module of nginx uses pcre to parse regular expressions, so it is necessary to install pcre library on linux. pcre devel is a secondary development library developed using pcre. Nginx also needs this library.
        • Install: Yum install - y PCRE devel
      • zlib
        • Purpose: zlib library provides many ways of compression and decompression. nginx uses zlib to gzip the contents of http package.
        • Install: Yum install - y zlib zlib devel
      • openssl,openssl-devel
        • Purpose: OpenSSL is a powerful secure socket layer cipher library, including main cipher algorithms, common key and certificate encapsulation management functions and SSL protocol, and provides rich applications for testing or other purposes. nginx supports not only http protocol, but also https (that is, http is transmitted over SSL Protocol).
        • Install: Yum install - y OpenSSL OpenSSL devel
    • General installation
      • gcc
        • Purpose: compile source code
        • Install: yum -y install gcc-c++
      • pcre
        • Purpose: rewrite Module
        • Website: pcre English official website
        • Download and install
          • Installation directory: cd /usr/src
          • Download: wget https://github.com/PhilipHazel/pcre2/releases/download/pcre2-10.39/pcre2-10.39.tar.bz2
          • Decompression: tar -xjvf pcre2-10.39.tar.bz2
          • install
            • cd pcre2-10.39
            • ./configure
            • make & make install
      • openssl
        • Purpose: ssl module
        • Website: openssl English official website
        • Download and install
          • Installation directory: cd /usr/src
          • Download: wget https://www.openssl.org/source/openssl-3.0.0.tar.gz
          • Unzip: tar -zxvf openssl-3.0.0.tar.gz
          • Installation:
            • cd openssl-3.0.0
            • ./config
            • make & make install
      • zlib
        • Purpose: gzip module
        • Website: zlib English official website
        • Download and install
          • Installation directory: cd /usr/src
          • Download: wget http://zlib.net/zlib-1.2.11.tar.gz
          • Decompression: tar -zxvf zlib-1.2.11.tar.gz
          • install
            • cd zlib-1.2.11
            • ./configure
            • make & make install
  • Installing nginx
    • Download and install
      • Installation directory: cd /usr/src
      • Download: wget http://nginx.org/download/nginx-1.20.0.tar.gz
      • Decompression: tar -zxvf nginx-1.20.0.tar.gz
      • install
        • cd nginx-1.20.0
        • ./configure --prefix=/usr/local/nginx --with-openssl=/usr/src --with-pcre=/usr/src --with-zlib=/usr/src --with-http_stub_status_module --with-http_ssl_module --with-http_v2_module --with-http_sub_module --with-http_gzip_static_module
        • make & make install
      • start-up
        • cd /usr/local/nginx/sbin
        • ./nginx
        • Visit 0.0.0.0:80

CLI

configure directive (nginx source file build directive)

  • Configure instruction: open the configure instruction in the source file storage directory / usr/src/nginx-1.20.0 /
    • --Help: output help information
    • --prefix=path: set the nginx installation directory. The default value is / usr/local/nginx
    • --With openssl = path: set the path of the source file used to install the openssl library
    • --With pcre = path: set the path of the source file used to install the pcre library
    • --With PCRE: set to force the use of PCRE libraries
    • --With zlib = path: set the path of the source file used to install the zlib library
    • --with-http_stub_status_module: sets the module that allows viewing nginx status
    • --with-http_ssl_module: set the module that supports https (i.e. transmitting HTTP over SSL Protocol)
    • --with-http_v2_module: sets the module that supports http/2
    • --with-http_sub_module: sets the string that supports changing the matching response
    • --with-http_gzip_static_module: set to support gzip function

Nginx instruction (nginx runtime instruction)

  • Nginx instruction: open sbin/nginx in the nginx installation directory / usr/local/nginx to execute the instruction
    • No parameters: start nginx service
    • -? | - h: Print help information
    • -c file: set the specified configuration file to replace the default configuration file. The default configuration file path is / usr/local/nginx/conf/nginx.conf
    • -e file: set the specified error log file to replace the default error log file
    • -g directives: set the global directives of the configuration file, such as nginx - G "PID / var / run / nginx. PID; worker_processes' sysctl - N HW. Ncpu ';"
    • -p prefix: sets the storage directory of nginx instructions, which is used to replace the default nginx instruction storage directory / usr/local/nginx
    • -q: Set to prohibit printing error messages during the execution of nginx configuration files
    • -s signal: Send a signal to the main process
      • stop: close the nginx service, (tough) this method is equivalent to finding out the nginx process id first, and then using the kill command to forcibly kill the process.
      • quit: close the nginx service, (gentle) the stop step in this way is to stop the nginx process after the processing task is completed. Note: to start the nginx service is to directly execute the nginx instruction without parameters.
      • Reload: restart nginx (this method is not recommended. It is recommended to stop before starting). It is generally used to reload the configuration file
      • Reopen: reopen the log file
    • -t: Test the configuration file for syntax errors
    • -T: Test the configuration file for syntax errors and print the contents of the configuration file
    • -v: Print nginx version
    • -5: Print nginx version, compiler version, and configuration parameters

configuration file

  • Configuration file: the default path of the configuration file is / usr/local/nginx/conf/nginx.conf
    • Configuration item
      • main module
        • Core module (Global module)
        • events module
        • http module
          • server
            • location

Embedded variable

  • $remote_addr: client IP address
  • $remote_user: client user name
  • $time_local: the access time and time zone of the current machine on the Nginx server
  • $request: URI and HTTP protocol of the request
  • $status: response status code
  • $body_ bytes_ Send: the content size of the response file sent to the client, excluding the response request header
  • $http_referer: url jump source
  • $http_user_agent: user terminal browser and other information

Configuration item

Core module (Global module)

  • daemon on | off
    • Purpose: set whether the nginx service is a daemon, which is mainly used for debugging the test environment.
    • Default value: daemon;
    • Context: main.
    • Note: do not use daemon and master_ The process instruction is used in the production environment. These configurations are mainly used for debugging the test environment.
daemon  off;
  • master_process on | off
    • Purpose: set whether the nginx service starts the worker process. This instruction is mainly applicable to nginx developers.
    • Default: master_process on;
    • Context: main.
    • Note: do not use daemon and master_ The process instruction is used in the production environment, and these configurations are mainly used in the test environment.
master_process  off;
  • debug_points abort | stop

    • Purpose: setting allows you to set breakpoints in the debugger for debugging. This instruction is used for debugging.
    • Default: none.
    • Context: main.
  • error_log file [level]

    • Purpose: set the error log configuration, which mainly records the error status of nginx processing http requests and the error status of nginx service running.
    • Default: error_log logs/error.log error;, The relative current path is prefix. Prefix defaults to / usr / local / nginx, that is, the nginx installation directory, that is, the default value is actually error_log /usr/local/nginx/logs/error.log error;
    • Context: main, http, mail, stream, server, location.
    • parameter
      • file: sets the error log path, which is logs/error.log by default, relative to prefix, that is, relative to the nginx installation directory, that is, the path is affected by the configure compilation parameter - prefix = < Path > instruction. If it is not specified, nginx is compiled in / usr/local/nginx by default.
      • Level: set the error log level, which is error by default. It is listed from low to high, from top to bottom. The low-level log display includes high-level logs, and the high-level log display does not include low-level logs, that is, the lower the level, the richer or redundant the display content. The log displayed by debugging and debugging contains all error information.
        • Debug: if you want to open this level of logs, you need to execute the parameter -- with debug when compiling nginx, that is, execute. / configure -- with debug in the source file directory to install nginx.
        • info
        • notice
        • warn
        • error
        • crit
        • alert
        • emerg
    • be careful
      • error_log /dev/null;: Completely shut down error_log
  • include file | mask

    • Purpose: set the included configuration file to include the split configuration file, or the file extension and file type mapping table file, such as mime.types (the corresponding relationship between mime type and file extension is generally placed in mime.types, and then loaded with include mime.types.
    • Default: none.
    • Context: any.
    • parameter
      • File: set the path of the included file, and error_ Unlike log, the file path of the current instruction is relative to the current directory path of the configuration file.
# /usr/src/nginx/conf/nginx.conf
include mime.types;
include vhosts/*.conf;

# /usr/src/nginx/conf/mime.types
types {
    text/html                                        html htm shtml;
    text/css                                         css;
    text/xml                                         xml;
    image/gif                                        gif;
    image/jpeg                                       jpeg jpg;
    application/javascript                           js;
    application/atom+xml                             atom;
    application/rss+xml                              rss;

    text/mathml                                      mml;
    text/plain                                       txt;
    text/vnd.sun.j2me.app-descriptor                 jad;
    text/vnd.wap.wml                                 wml;
    text/x-component                                 htc;

    image/png                                        png;
    image/svg+xml                                    svg svgz;
    image/tiff                                       tif tiff;
    image/vnd.wap.wbmp                               wbmp;
    image/webp                                       webp;
    image/x-icon                                     ico;
    image/x-jng                                      jng;
    image/x-ms-bmp                                   bmp;

    application/font-woff                            woff;
    application/java-archive                         jar war ear;
    application/json                                 json;
    application/mac-binhex40                         hqx;
    application/msword                               doc;
    application/pdf                                  pdf;
    application/postscript                           ps eps ai;
    application/rtf                                  rtf;
    application/vnd.apple.mpegurl                    m3u8;
    application/vnd.google-earth.kml+xml             kml;
    application/vnd.google-earth.kmz                 kmz;
    application/vnd.ms-excel                         xls;
    application/vnd.ms-fontobject                    eot;
    application/vnd.ms-powerpoint                    ppt;
    application/vnd.oasis.opendocument.graphics      odg;
    application/vnd.oasis.opendocument.presentation  odp;
    application/vnd.oasis.opendocument.spreadsheet   ods;
    application/vnd.oasis.opendocument.text          odt;
    application/vnd.openxmlformats-officedocument.presentationml.presentation
                                                     pptx;
    application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
                                                     xlsx;
    application/vnd.openxmlformats-officedocument.wordprocessingml.document
                                                     docx;
    application/vnd.wap.wmlc                         wmlc;
    application/x-7z-compressed                      7z;
    application/x-cocoa                              cco;
    application/x-java-archive-diff                  jardiff;
    application/x-java-jnlp-file                     jnlp;
    application/x-makeself                           run;
    application/x-perl                               pl pm;
    application/x-pilot                              prc pdb;
    application/x-rar-compressed                     rar;
    application/x-redhat-package-manager             rpm;
    application/x-sea                                sea;
    application/x-shockwave-flash                    swf;
    application/x-stuffit                            sit;
    application/x-tcl                                tcl tk;
    application/x-x509-ca-cert                       der pem crt;
    application/x-xpinstall                          xpi;
    application/xhtml+xml                            xhtml;
    application/xspf+xml                             xspf;
    application/zip                                  zip;

    application/octet-stream                         bin exe dll;
    application/octet-stream                         deb;
    application/octet-stream                         dmg;
    application/octet-stream                         iso img;
    application/octet-stream                         msi msp msm;

    audio/midi                                       mid midi kar;
    audio/mpeg                                       mp3;
    audio/ogg                                        ogg;
    audio/x-m4a                                      m4a;
    audio/x-realaudio                                ra;

    video/3gpp                                       3gpp 3gp;
    video/mp2t                                       ts;
    video/mp4                                        mp4;
    video/mpeg                                       mpeg mpg;
    video/quicktime                                  mov;
    video/webm                                       webm;
    video/x-flv                                      flv;
    video/x-m4v                                      m4v;
    video/x-mng                                      mng;
    video/x-ms-asf                                   asx asf;
    video/x-ms-wmv                                   wmv;
    video/x-msvideo                                  avi;
}
  • pid file

    • Purpose: set the file path used to store the main process ID. The relative current path is prefix. Prefix defaults to / usr / local / nginx, that is, the nginx installation directory, that is, the default value is actually error_log /usr/local/nginx/logs/nginx.pid;
    • Default value: pid logs/nginx.pid;
    • Context: main.
  • ssl_engine device

    • Purpose: set the engine used to specify openssl. You can get the openssl engine currently supported by the system through the command openssl engine -t.
    • Default: None
    • Context: main.
  • timer_resolution interval

    • Purpose: reduce timer resolution in worker processes, thus reducing the number of gettimeofday() system calls made. By default, gettimeofday() is called each time a kernel event is received. With reduced resolution, gettimeofday() is only called once per specified interval
    • Default: None
    • Context: main.
timer_resolution 100ms;
  • user user [group]

    • Purpose: set the running user and user group of the Nginx Worker process. The default is the nobody account.
    • Default value: user nobody nobody;
    • Context: main.
    • parameter
      • User: Specifies the user
      • Group: Specifies the user group. If this option is ignored, it defaults to the user group of the specified user
  • worker_cpu_affinity cpumask ..., worker_cpu_affinity auto [cpumask]

    • Purpose: only applicable to linux. Use this option to bind worker process and CPU.
    • Default: None
    • Context: main.
# Bind a CPU to each worker process
worker_proceses     4;
worker_cpu_affinity 0001 0010 0100 1000;

# Bind CPU0/CPU2 to the first worker process and CPU1/CPU3 to the second worker process.
worker_proceses     2;
worker_cpu_affinity 0101 1010;
  • worker_priority number
    • Purpose: use this option to assign priority values to all worker processes.
    • Default: worker_priority 0;
    • Context: main.
    • parameter
      • number: - 20 to 20
worker_priority -10;
  • worker_processes number | auto

    • Purpose: set the number of worker processes used by nginx service, which is generally set to the number of cpu cores
    • Default: worker_processes 1;
    • Context: main.
    • parameter
      • number: - 20 to 20, or auto, The auto parameter is supported starting from versions 1.3.8 and 1.2.5
  • worker_rlimit_core size

    • Purpose: changes the limit on the large size of a core file (rlimit_core) for worker processes. Used to increase the limit without restarting the main process
    • Default: None
    • Context: main.
  • worker_rlimit_nofile number

    • Purpose: Changes the limit on the maximum number of open files (RLIMIT_NOFILE) for worker processes. Used to increase the limit without restarting the main process
    • Default: None
    • Context: main.
  • worker_shutdown_timeout time

    • Purpose: this directive appeared in version 1.11.11. Configure a timeout for a decent shutdown of worker processes. When the time expires, nginx will try to close all the connections currently open to facilitate shutdown
    • Default: None
    • Context: main.
  • working_directory directory

    • Purpose: defines the current working directory for a worker process. It is primarily used when writing a core file, in which case a worker process should have write permission for the specified directory
    • Default: None
    • Context: main.

events module

  • accept_mutex on | off

    • Purpose: nginx uses connection mutex to make sequential accept() system calls
    • Default: on
    • Context: events
  • accept_mutex_delay time

    • Purpose: when accept_ When mutex is started, if a process does not have a mutex, this configuration item is used to set the delay for reconnection. By default, the delay is 500ms.
    • Default: accept_mutex_delay 500ms;
    • Context: events
  • debug_connection address | CIDR | unix:;

    • Purpose: Enables debugging log for selected client connections. Other connections will use logging level set by the error_log directive. Debugged connections are specified by IPv4 or IPv6 (1.3.0, 1.2.1) address or network. A connection may also be specified using a hostname. For connections using UNIX-domain sockets (1.3.0, 1.2.1), debugging log is enabled by the “unix:” parameter.
    • Default: None
    • Context: events
    • Note: for this directive to work, nginx needs to be built with -- with debug, see "A debugging log"
events {
    debug_connection 127.0.0.1;
    debug_connection localhost;
    debug_connection 192.0.2.0/24;
    debug_connection ::1;
    debug_connection 2001:0db8::/32;
    debug_connection unix:;
    ...
}
  • multi_accept on | off

    • Purpose: if accept_mutex prohibits a worker process from allowing only one new connection at a time. Otherwise, a worker process allows all new connections at a time.
    • Default: multi_accept off;
    • Context: events
  • use method

    • Purpose: if more than one event model is specified in. / configure, you can set one of them to tell nginx which event model to use. By default, nginx will find the most suitable event model for the system at. / configure.
    • Default: None
    • Context: events
    • parameter
      • method: kqueue | rtsig | epoll | /dev/poll | select | poll | eventport
  • worker_connections number

    • Purpose: set the maximum number of concurrent connections that a worker process can open. Through worker_connections and worker_ Processes can calculate maxclients: max_clients = worker_processes * worker_connections
    • Default: worker_connections 512;
    • Context: events

http module

ngx_http_core_module
  • default_type mime-type
    • Purpose: set the corresponding default file type. If the request message of the client Web program is not set, and the Nginx service of the server does not have the extension of the corresponding file (that is, there is no file suffix matching of this response in the file of include mime.types), use the default in Nginx_ Type defines the processing method.
    • Default: default_type text/plain;
    • Context: http, server, location
location = /proxy.pac {
    default_type application/x-ns-proxy-autoconfig;
}
location = /wpad.dat {
    rewrite . /proxy.pac;
    default_type application/x-ns-proxy-autoconfig;
}
  • sendfile on | off
    • Purpose: set whether sendfile() is allowed.
    • Default value: sendfile off;
    • Context: http, server, location, if in location
location /video/ {
    sendfile       on;
    tcp_nopush     on;
    aio            on;
}
  • tcp_nopush on | off

    • Purpose: set to allow TCP in FreeBSD_ Nopush socket, or whether TCP is allowed in Linux_ Cork socket, this option depends on the sendfile configuration item to be started.
    • Default: tcp_nopush off;
    • Context: http, server, location
  • keepalive_timeout timeout [header_timeout]

    • Purpose: set to allow TCP in FreeBSD_ Nopush socket, or whether TCP is allowed in Linux_ Cork socket, this option depends on the sendfile configuration item to be started.
    • Default: keepalive_timeout 75s;
    • Context: http, server, location
    • parameter
      • timeout: sets the length of time that the Nginx service maintains a long connection. If it is set to 0, the long connection will be closed
      • header_timeout: set the response request header keep alive: timeout = time, which is applicable to Mozilla and Konqueror
ngx_http_log_module
  • log_format name [escape=default|json|none] string ...

    • Purpose: define record log format (multiple log formats can be defined, just take different name s)
    • Default value: log_format combined '$remote_addr - $remote_user [$time_local] "$request" $status $body_bytes_sent "$http_referer" "$http_user_agent";
    • Context: http
    • parameter
      • Name: the name of the defined log format in access_ Reference in log instruction
      • escape: sets whether the character encoding method in the variable is json or default. The default is default.
        • Default: the default value, escape ", \ and characters with character encoding value less than 32 or greater than 126 are in \ xXX format. If the character encoding value does not exist, the log will be printed as -.
        • JSON: all characters that do not match JSON characters will be escaped, ", \ will be escaped as \", \ \, and character encoding values less than 32 will be escaped as \ n, \ R \ T, \ B, \ f or \ u00XX.
        • none: escape is not allowed.
      • string: the content of the log format to be defined. This parameter can have multiple. Nginx embedded variables can be used in the parameters.
  • access_log path name [format [buffer=size] [gzip[=level]] [flush=time] [if=condition]], access_log off

    • Purpose: to record the access status of each http request of nginx, which is mainly used to analyze the request of each access and the interaction behavior of the client.
    • Default value: access_log logs/access.log combined
    • Context: http, server, location, if in location, limit_except
    • parameter
      • Path: access log file path
      • name: set the log format. You can use the custom log format set by log_format
      • format
        • Buffer: sets the size of the buffer for storing access logs
        • gzip: set compression level
        • flush: sets the time when the log of the buffer is flushed to the disk
        • if: set other conditions
    • Note: to close the access log, use the command access_log off
ngx_http_gzip_module
  • gzip on | off
    • Purpose: set whether Gzip is used for response.
    • Default value: gzip off;
    • Context: http, server, location, if in location
ngx_http_index_module
  • index file ...
    • Purpose: set the default home page of HTTP server. When the instruction value is multiple files, it will be searched from left to right, and the search will end when the corresponding file is found.
    • Default value: index.html;
    • Context: http, server, location
location / {
    index index.$geo.html index.html;
}
ngx_http_proxy_module
  • proxy_pass URL
    • Purpose: set the protocol, IP address or socket to connect to the proxy server. It can also be a domain name or a server group defined by upstream
    • Default: None
    • Context: location, if in location, limit_except
location / {
    proxy_pass $scheme://$http_host$request_uri; # proxy to remote server
}
ngx_http_fastcgi_module
  • fastcgi_pass address

    • Purpose: set the default index file
    • Default: None
    • Context: location, if in location
  • fastcgi_index name

    • Purpose: set the IP address or socket of FastCGI server, or the domain name or server group defined by upstream
    • Default: None
    • Context: http, server, location
  • fastcgi_param parameter value [if_not_empty]

    • Sets a parameter that should be passed to the fastcgi server. The value can contain text, variables, and their combination. These directives are inherited from the previous configuration level if and only if there are no fastcgi_parameter directives defined on the current level
    • Default: None
    • Context: http, server, location
# Nginx implements load balancing based on FastCGI

upstream fscgi_server {
    ip_hash;                               # session hold
    server 192.168.2.145:9000;             # PHP-FPM server IP
    server 192.168.2.159:9000;             # PHP-FPM server IP
}

fastcgi_cache_path /usr/local/nginx/nginx-cache1
                            levels=1:2
                            keys_zone=fscgi_hdd1:100m
                            max_size=10g
                            use_temp_path=off
                            inactive=60m;    # Set cache storage path 1, shared memory name and size of cache
                                             # 100MB, the judgment time of invalid cache is 1 hour

fastcgi_cache_path /usr/local/nginx/nginx-cache2
                            levels=1:2
                            keys_zone=fscgi_hdd2:100m
                            max_size=10g
                            use_temp_path=off
                            inactive=60m;   # Set cache storage path 2, shared memory name and size of cache
                                            # 100MB, the judgment time of invalid cache is 1 hour

split_clients $request_uri $fscgi_cache {
              50%           "fscgi_hdd1";  # 50% of the requested cache is stored on the first disk
              50%           "fscgi_hdd2";  # 50% of the requested cache is stored on the second disk
}

server {
    listen 8080;
    root /opt/nginx-web/phpweb;
    index index.php;
    include        fscgi.conf;             # Import default profile
   
    location ~ \.(gif|jpg|png|htm|html|css|js|flv|ico|swf)(.*) {  # Static resource file expiration time
                                                                  # 12 hours
        expires      12h;
    }

    set $no_cache 0;
    if ($query_string != "") {              # Data without URI parameters is not cached
        set $no_cache 1;
    }

    location ~ \.php(.*)$ {
        root /opt/nginx-web/phpweb;

        fastcgi_cache $fscgi_cache;        # Enable $fscgi_cache for fastcgi_cache_path setting
                                           # Shared memory area for caching
        fastcgi_cache_key ${request_method}://$host$request_uri; # set the keyword of the cache
        fastcgi_cache_lock on;             # Enable cache lock
        fastcgi_cache_lock_age 5s;         # When cache lock is enabled, the processing time of adding cache request is 5s
        fastcgi_cache_lock_timeout 5s;     # The timeout for waiting for cache lock is 5s
        fastcgi_cache_methods GET HEAD;    # By default, GET and HEAD method requests are cached
        fastcgi_cache_min_uses 1;          # The response data will be cached once requested

        fastcgi_no_cache $no_cache;        # $no_cache does not cache the current request
        fastcgi_cache_bypass $no_cache;    # $no_cache does not cache the current request

        fastcgi_cache_use_stale error timeout invalid_header
                                updating http_500 http_503
                                http_403 http_404 http_429;        # When a specified condition occurs, use
                                                                   # Cached response data that has expired
        fastcgi_cache_background_update on; # When expired response data is allowed to be used, the back table subrequest is enabled for
                                            # Update the expired cache and return the expired cache response data to the client

        fastcgi_cache_revalidate on;       # When the cache expires, an If is initiated to the backend server-
                                           # Modified since and if none match HTTP messages
                                           # Server verification of header field
        fastcgi_cache_valid 200 301 302 10h; # 200 301 302 status code response cache for 10 hours
        fastcgi_cache_valid any 1m;        # The response of other status codes is cached for 1 minute

        add_header X-Cache-Status $upstream_cache_status;   # View cache hit status

        fastcgi_pass   fscgi_server;
        fastcgi_index  index.php;
        fastcgi_split_path_info       ^(.+\.php)(.*)$;      # Get the value of $fastcgi_path_info variable
        fastcgi_param PATH_INFO       $fastcgi_path_info;   # Assign to parameter PATH_INFO
        include        fastcgi.conf;                        # Import default parameter file
    }

    error_page 404 /404.html;
    error_page 500 502 503 504 /50x.html;
}
ngx_http_upstream_module
  • upstream name { ... }
    • Purpose: load balancing configurations such as server and load balancing policy can be set in the instruction domain
    • Default: None
    • Context: http
    • be careful
      • Nginx load balancing: it is jointly implemented by the proxy module and the upstream module. Nginx forwards user requests to the upstream server group through the reverse proxy function of the proxy module. The upstream module forwards user requests to the target server through the specified load balancing strategy and related parameter configuration. The upstream module can communicate with the proxy_pass of nginx , fastcgi_pass, uwsgi_pass, scgi_pass, memcached _passand gRPC _passrealize the load balancing of various protocol backend servers.
upstream backend {
    server backend1.example.com       weight=5;     # The port number of the proxy server is 80 and the weight is 5
    server backend2.example.com:8080;               # The port number of the proxy server is 8080, and the default weight is 1
    server unix:/tmp/backend3;

    server backup1.example.com:8080   backup;       # The proxy server is in backup status
    server backup2.example.com:8080   backup;       # The proxy server is in backup status
}

server {
    location / {
        proxy_pass http://backend;          #  Reverse proxy client requests to upstream server group backend
    }
}
  • Virtual service instruction parameters

server
  • server { ... }

    • Purpose: Nginx is used to define service IP, binding port and service related instruction area
    • Default: None
    • Context: http
  • listen

    • Purpose: configuration of service listening port, binding IP and listening mode
    • usage
      • listen address[:port] [default_server] [ssl] [http2 | spdy] [proxy_protocol] [setfib=number] [fastopen=number] [backlog=number] [rcvbuf=size] [sndbuf=size] [accept_filter=filter] [deferred] [bind] [ipv6only=on|off] [reuseport] [so_keepalive=on|off|[keepidle]:[keepintvl]:[keepcnt]];
      • listen port [default_server] [ssl] [http2 | spdy] [proxy_protocol] [setfib=number] [fastopen=number] [backlog=number] [rcvbuf=size] [sndbuf=size] [accept_filter=filter] [deferred] [bind] [ipv6only=on|off] [reuseport] [so_keepalive=on|off|[keepidle]:[keepintvl]:[keepcnt]];
      • listen unix:path [default_server] [ssl] [http2 | spdy] [proxy_protocol] [backlog=number] [rcvbuf=size] [sndbuf=size] [accept_filter=filter] [deferred] [bind] [so_keepalive=on|off|[keepidle]:[keepintvl]:[keepcnt]];
    • Default value: listen *:80 | *:8000;, The default port number of super administrator is 80, and that of other users is 8000
    • Context: server
    • parameter
      • Address: if only the IP address is set but no port is set, the default port number of super administrator is 80 and that of other users is 8000
      • default_server: when the http domain contains multiple virtual hosts (i.e. multiple server blocks), this parameter is used to specify which virtual host is the default service. If this configuration item is not set, the server in the first order will be set as the default service. The default service can be used to handle no server_name matches the successful request
      • SSL: SSL support
      • http2: HTTP/2 protocol support
      • spdy: SDPY protocol support. It cannot exist with HTTP/2 protocol at the same time
      • proxy_protocol: enable proxy on the specified listening port_ Protocol support
      • setfib=number: sets the associated routing table for the listening socket. It is only valid on the FreeBSD system
      • fastopen=number: the maximum number of queues for TCP connections that are allowed without three handshakes when HTTP is in the keep alive state
      • backlog=number: when blocking, set the maximum length of the pending connection queue. The default value is - 1 on FreeBSD, DragonFly BSD and MacOS operating systems, and 511 on other platforms
      • rcvbuf=size: the size of socket receiving buffer, which is 8k bytes by default. It can be adjusted appropriately in the scenario of large received data
      • sndbuf=size: the size of socket sending buffer, which is 8k bytes by default. It can be adjusted appropriately in scenarios with large sending data
      • accept_filter=filter: the default value is filter, which sets a filter for listening sockets. Only FreeBSD and NetBSD 5.0 + systems are supported
      • deferred: after adding this parameter, the TCP state is set to ESTABLISHED only when the client is detected to have data during the three TCP handshakes. If there is no data, it is directly discarded
      • bind: Specifies the IP and port
      • IPv6 only = on off: only receive IPv6 connections or receive IPv6 and IPv4 connections
      • Reuse port: by default, all working processes will share a socket to listen to the same combination of IP and port. When this parameter is enabled, each working process is allowed to have an independent socket to listen to the combination of the same IP and port, and the kernel will load balance the connection of the sender. For Linux 3.9 +, DragonFly BSD and FreeBSD 12+
      • so_keepalive=on|off|[keepidle]:[keepintvl]:[keepcnt]: the default value is off. Configure whether to enable the "TCP keepalive" mechanism on the listening port. When set to on, it is equivalent to so by default_ Keepalive = 30m:: 10, which means that the probe packet is sent 10 times when there is no data transmission in 30 minutes. The sending interval uses the system kernel parameter TCP_ keepalive_ Setting value of intvl
http {
    server {
        listen 127.0.0.1:8000;           # Listen to port 8000 of 127.0.0.1
        listen 127.0.0.1;                # Listen to the default port 80 of 127.0.0.1 (root permission)
        listen 8000;                     # Listen to 8000 ports of all local IP addresses
        listen *:8000;                   # Listen to 8000 ports of all local IP addresses
        listen localhost:8000;           # Listen to port 8000 of locahost
        listen [::]:8000;                # Listen to the 8000 port of IPv6
        listen [::1];                    # Listen to the default port 80 of IPv6 loopback IP (root permission)
        listen unix:/var/run/nginx.sock; # Listening domain socket file

        listen *:8000 \                  # Listen to the 8000 port of this machine
                default_server \         # The current service is the main service of the http instruction domain
                fastopen=30 \            # Enable the fastopen function and limit the maximum number of queues to 30
                deferred \               # Reject empty data connection
                reuseport \              # Worker processes share the socket listening port
                backlog=1024 \           # The number of pending queues when blocking requests is 1024
                so_keepalive=on;         # When the socket remains connected, turn on the status detection function
    }
}
# IPv6 addresses (0.7.36) are specified in square brackets:
listen [::]:8000;
listen [::1];

# UNIX-domain sockets (0.8.21) are specified with the "unix:" prefix:
listen unix:/var/run/nginx.sock;
  • server_name name ...
    • Purpose: set the virtual host name of the server instruction domain. When the server_ When there are multiple host names in the name instruction value, the first host name is the first host name.
    • Default: server_name "";
    • Context: server
http {
    server {
        server_name example.com .example.com;       # Use of Pan domain names
        server_name www.example.;                   # Use of multiple suffix domain names_ name
        www.example.com ~^www.example.com$;         # Regular Expression Matching 
        # Scenario of regular matching variables
        server_name ~^(www\.)?(.+)$;
        location / {
            root /sites/$2;
        }

        # Scenario with regular matching as variable
        server_name ~^(www\.)?(?<domain>.+)$;
        location / {
            root /sites/$domain;
        }
    }
}
  • error_page code ... [=[response]] uri
    • Purpose: when an error occurs in an HTTP request, you can define a returned page or perform jump according to the response status code.
    • Default: None
    • Context: http, server, location, if in location
error_page 404             /404.html;
error_page 500 502 503 504 /50x.html;
error_page 404 = @fallback;
location
  • location [ = | ~ | ~* | ^~ ] uri { ... }
    • Purpose: tell the client to jump to the specified URI.
    • Default: None
    • Context: server, location
    • parameter
      • =: indicates an exact match
      • ^~: indicates that the uri starts with a regular string, which can be understood as matching the url path. nginx does not encode the url, so the request is / static/20%/aa, which can be matched by the rule ^ ~ / static/ /aa (note the space). Start with xx
      • ~: indicates a case sensitive regular match, ending with xx
      • ~*: indicates a case insensitive regular match, ending with xx
      • !~: Case sensitive mismatch
      • !~*: Case insensitive mismatched regular
      • /: general matching, any request will be matched
      • Matching rules: exact matching = - > followed by matching starting with xx ^ ~ - > followed by regular matching according to the order in the file - > finally handed over to / general matching. When there is a successful matching, stop matching and process the request according to the current matching rules
# /usr/local/nginx/conf/nginx.conf
location = / {
   # Rule A
}
location = /login {
   # Rule B
}
location ^~ /static/ {
   # Rule C
}
location ~ \.(gif|jpg|png|js|css)$ {
   # Rule D, note: matching is based on the case in parentheses. The brackets are all lowercase and match only lowercase
}
location ~* \.png$ {
   # Rule E
}
location !~ \.xhtml$ {
   # Rule F
}
location !~* \.xhtml$ {
   # Rule G
}
location / {
   # Rule H
}
# The effects are as follows:
# Access the root directory /, such as http://localhost/  Match rule A
# visit http://localhost/login  Will match rule B, http://localhost/register  Then match rule H
# visit http://localhost/static/a.html  Match rule C
# visit http://localhost/a.gif, http://localhost/b.jpg  Rule D and rule E will be matched, but rule D takes precedence, rule E does not work, and http://localhost/static/c.png  Then it is preferentially matched to rule C
# visit http://localhost/a.PNG  Then match rule E, not rule D, because rule E is not case sensitive
# visit http://localhost/a.xhtml  Will not match rule F and rule G, http://localhost/a.xhtml Rule G will not be matched, (because!). Rule F and rule G belong to the exclusion method. If they meet the matching rules, they will not be matched, so think about where they will be used in practical applications.
# visit http://localhost/category/id/1111 Then it will eventually match rule H, because none of the above rules match. At this time, nginx forwards the request to the back-end application server, such as FastCGI (php), tomcat (jsp), and nginx exists as the direction proxy server.
# Directly match the website root and visit the website home page through the domain name more frequently. Using this will speed up the processing.
# This is directly forwarded to the back-end application server, or it can be a static home page
# First required rule
location = / {
    proxy_pass http://tomcat:8080/index
}

# The second required rule is to handle static file requests, which is the strength of nginx as an http server
# There are two configuration modes, directory matching or suffix matching. Choose one or use it together
location ^~ /static/ {                              //Start with xx
    root /webroot/static/;
}
location ~* \.(gif|jpg|jpeg|png|css|js|ico)$ {     //End with xx
    root /webroot/res/;
}
 
# The third rule is the general rule, which is used to forward dynamic requests to the back-end application server
# Non static file requests are dynamic requests by default. You can grasp them according to the actual situation
location / {
    proxy_pass http://tomcat:8080/
}
  • root path
    • Purpose: set the local file root directory of the request URL. When the root instruction is in the location instruction domain, root sets the upper directory of the location matching access path
    • Default: root html;
    • Context: http, server, location, if in location
# The actual local path of the request file is / data/web/flv/
location /flv/ {
    root /data/web;
}

application

survey

  • journal
    • error.log: through the configuration item error_log setting, which mainly records the error status of nginx processing http requests and the error status of nginx service operation.
    • access.log: access through the configuration item_ Log and log_ The format setting records the access status of each http request of nginx, which is mainly used to analyze the request of each access and the interaction behavior of the client.

scene

practice

Example

Official example

#Official example

#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;
    #    }
    #}

}

Direction proxy

# Reverse proxy example 1
# 192.168.1.100:8901 -> http://192.168.1.101:8099
# Reverse proxy example 2
# 192.168.1.100:8902/101/index.html -> http://192.168.1.101:8099/dist/index.html
# 192.168.1.100:8902/102/index.html -> http://192.168.1.102:8099/dist/index.html

worker_processes  1;

events {
    worker_connections  1024;
}

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

    sendfile      on;
    keepalive_timeout  65;

    server {
        listen       8901;
        server_name  192.168.1.100;
        location / {
            proxy_pass http://192.168.1.101:8099;
        }
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }
    server {
        listen 8902;
        server_name 192.168.1.100;
        location / {
            proxy_pass http://192.168.1.102:8099;
        }
        location ^~ /101/ {
            proxy_pass http://192.168.1.101:8099/dist/;
        }
        location ^~ /102/ {
            proxy_pass http://192.168.1.102:8099/dist/;
        }
    }
}

reference

High availability
nginx infrastructure

Tags: Operation & Maintenance

Posted on Sun, 21 Nov 2021 15:29:53 -0500 by randomfool