Web Front-end Necessary-Nginx Knowledge Summary

Posted by trixiesirisheyes on Wed, 15 May 2019 20:31:23 +0200

Introduction to Nginx

Nginx is a high-performance, lightweight Web and reverse proxy server, which has the characteristics of less memory and resources, and strong concurrency resistance.

Nginx is simple to install, simple to configure, fast and convenient to start, supports hot deployment, supports SSL, and has a highly modular design.

The main functions of Nginx are:

  • Web server
  • Reverse proxy
  • load balancing

II. Operation and Control of Nginx

Note: In the following command, / usr/local/nginx is the absolute path of nginx binary file, which depends on its actual installation path.

1. boot

/usr/local/nginx/sbin/nginx

2. Reopen the log file

/usr/local/nginx/sbin/nginx -s reopen

3. Reload the configuration file

/usr/local/nginx/sbin/nginx -s reload

4. stop

/usr/local/nginx/sbin/nginx -s stop

5. Stop calmly

(1) View process number

ps -ef|grep nginx

(2) Killing process

Kill-QUIT < process number > or kill-TERM < process number >

6. Forced cessation

pkill -9 nginx

3. Nginx as Web Server

As a Web server, Nginx needs to define server virtual hosts to handle requests for specific domain names or IP addresses.
Each server virtual host defines the location instruction, which defines how to match and process a specified set of URI s.

1. Basic examples of web servers

server {
  listen 80;
  server_name www.example.com;
  location / {
  root /usr/local/www;
      index index.html;
  }    
}

Description of parameters:

  • server represents a virtual host and can have more than one
  • Ser_name matches the specified domain name or IP address of the request
  • location configures the route of the request to match the corresponding URI
  • The path of root to find resources (folder directory)
  • index default lookup

2.location matching rules (request filtering)

(1) grammar

server {
   location Expression {
   }
}

(2) Types of location expressions

  • @ It defines a named location, using internal orientation, such as error_page, try_files
  • / Universal matching, any request will match to
  • = At the beginning, it means an exact match, and only if the url path of the request is exactly equal to the string after = will it match (with the highest priority)
  • ^~ Represents a common character match. Use prefix matching. If the match succeeds, no other location s are matched.
  • ~ Beginning with case-sensitive regular matching
  • ~* A regular case-insensitive match at the beginning

(3) Priority of location expressions

  • = Priority is highest. Once the match is successful, no other matches are found.
  • ^~ Type expression. Once the match is successful, no other matches are found.
  • ~ Priorities of * and * are next. If there are multiple location s whose rules match, the longest regular expression is used.
  • Conventional string matching type. Match by prefix.

3.URL rewrite

URL rewriting means that when the requested URL satisfies a pre-defined rule, it will jump/orient to a rule, such as common pseudo-static, 301 redirection, browser orientation, etc.

(1) grammar

server {
   rewrite Rule Oriented Path Rewrite Type;
}

rewrite parameter description:

  • Rules: Strings or regularities to represent the target url that you want to match
  • Directional path: The path to be directed after matching to a rule. If there is a rule in the rule, you can use $index to represent the capture group in the rule.
  • Rewrite type:

    • last: Represents that rewrite has been completed, the browser address bar URL address remains unchanged
    • After this rule matching is completed, the matching is terminated, and the following rules are no longer matched, and the URL address of the browser address bar remains unchanged.
    • redirect: Returns 302 temporary redirects, and the browser address displays the jumped URL address
    • Permanent: Returns 301 permanent redirection, and the browser address bar displays the jumped URL address

(2) example

Domain name jump: visit www.aaa.com and jump to www.bbb.com

server {
  listen 80;
  server_name  www.aaa.com;
  location / {
   rewrite ^/$ www.bbb.com permanent ;
  }
}

4.try_files

try_files refers to checking the existence of a file in sequence and returning the first file found. If all files are not found, an internal redirection is made to the last parameter.


(1) grammar

try_files file1 files2 ... uri

Description of parameters:

  • The last parameter is the fallback URI, which must exist or there will be an internal 500 error.
  • Only the last parameter can cause an internal redirection, and the previous parameter only sets the direction of the internal URI.
  • The last parameter can also be a named location.
  • If the last parameter is not named location, then $args will not be automatically retained. If you want to retain $args, you must explicitly state it in the last parameter. The example is:
try_files $uri $uri/ /index.php?q=$uri&$args;

(2) example

  • Jump to a file

When visiting: www.example.com/test, it will be searched in turn. If 1.html and 2.html do not exist, it will eventually return to 3.html.

server {
  listen 80;
  server_name www.example.com;
  root html;
  index index.html;
  location /test {
        try_files /1.html /2.html /3.html;
    }
}
  • Jump to variables

When visiting: www.example.com/test, it will be searched in turn. If 1.html and 2.html do not exist, it will jump to the location named abc.

server {
  listen 80;
  server_name www.example.com;
  root html;
  index index.html;             
  location /test {
      try_files /1.html /2.html @abc;
  }
  location @abc{
      rewrite ^/(.*)$  http://www.example2.com;
  }
}
  • When vue-router sets HTML5 History mode, nginx is configured as follows:
location / {
    # The URL does not match any static resources and returns to the same index.html page, which your app relies on.
    try_files $uri $uri/ /index.html;
}

5.Gzip configuration

server {
  # Open gzip compression
  gzip on;
  # Setting the minimum version of http protocol required for gzip (HTTP/1.1, HTTP/1.0)
  gzip_http_version 1.1;
  # Setting compression level (1-9), the larger the value, the higher the compression rate, and the more cpu resources are consumed. It is suggested that the compression level be set at about 4.
  gzip_comp_level 4;
  # Set the minimum number of bytes compressed, and get Content-Length from the page
  gzip_min_length 1000;
  # Set the type of compressed file (text/html), and do not recommend compressed pictures (such as jpg, png itself compressed)
  gzip_types text/plain application/javascript text/css;
 #Configuration disables gzip conditions to support regularization. This means that gzip is not enabled for ie6 and below (because the lower version of ie does not support it)
 gzip_disable "MSIE [1-6]\.";
}

6.https configuration

http {
  # Configure the size of shared session cache, depending on site access
  ssl_session_cache   shared:SSL:10m;
  # Configure session timeout
  ssl_session_timeout 10m;
  server {
    listen 443;
    server_name www.example.com;
    ssl on;
    # Setting Long Connections
    keepalive_timeout 70;
    # HSTS strategy
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;
    # Certificate file
    ssl_certificate www.example.com.crt;
    # Private key file
    ssl_certificate_key www.example.com.key;  
    # Prioritize Server Algorithms
    ssl_prefer_server_ciphers on;
    # Specify the SSL protocol
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    # Definition algorithm
    ssl_ciphers "EECDH+ECDSA+AESGCM EECDH+aRSA+AESGCM EECDH+ECDSA+SHA384 EECDH+ECDSA+SHA256 EECDH+aRSA+SHA384 EECDH+aRSA+SHA256 EECDH+aRSA+RC4 EECDH EDH+aRSA !aNULL !eNULL !LOW !3DES !MD5 !EXP !PSK !SRP !DSS !RC4";
    # Reduce click hijacking
    add_header X-Frame-Options DENY;
    # Disable server from automatically resolving resource types
    add_header X-Content-Type-Options nosniff;
    # Anti XSS attack
    add_header X-Xss-Protection 1;
  }
}

4. Nginx as a reverse proxy server

server {
  listen 80;
  server_name www.example.com;
  root html;
  index index.html;  
  location /test {    
    # Request host
    proxy_set_header Host $http_host;
    # Request ip
    proxy_set_header X-Real-IP $remote_addr;
    # Request agreement
    proxy_set_header X-Scheme $scheme;
    # proxy server
    proxy_pass http://localhost:3000;
  }
}

When visiting At http://www.example.com/test, nginx forwards the request to http://localhost 3000.

V. Nginx as Load Balancing

1. Introduction of Load Balancing

In server cluster, Nginx acts as a proxy server (reverse proxy). In order to avoid too much pressure on a single server, requests from users are forwarded to different servers.

Load balancing is used to select a server from the list of back-end servers defined by the "upstream" module to accept user requests.

2. Basic examples of load balancing

(1) upstream module

A basic upstream module is as follows:

#Dynamic server group, server is the back-end server, my_server is the name of the customized server group.
upstream my_server {
  server localhost:8001;
  server localhost:8002;
  server localhost:8003;
}

(2) Reverse Agency

After the upstream module configuration is completed, the specified access is reverse proxied to the server group.

server {
  listen 80;
  server_name www.example.com;
  root html;
  index index.html;
  location / {    
   # Reverse proxy to defined server group my_server
   proxy_pass my_server;
  }
}

(3) Complete configuration

http {
    upstream my_server {
    server localhost:8001;
    server localhost:8002;
    server localhost:8003;
  }
    server {
    listen      80;
    server_name www.example.com;
    root html;
    index index.html;
        location / {
            # Reverse proxy to defined server group my_server
            proxy_pass my_server;
        }
    }
}

3. Load Balancing Strategy

(1) Polling (default)

Indicates that each request is allocated to a different back-end server in chronological order.

upstream my_server {
   server localhost:8001;
   server localhost:8002;
}

(2) Weight

Represents the weight of the polling server specified on the basis of the polling policy, defaulting to 1. The higher the weight, the more requests to be processed.

upstream my_server {
  server localhost:8001 weight=1;
  server localhost:8002 weight=2;
}

(3) ip_hash

Represents that the specified load balancer is allocated in a client IP-based manner, which ensures that requests from the same client are always sent to the same server to ensure session session session. In this way, each visitor can access a back-end server regularly, which can solve the problem that session can not cross the server.

upstream my_server {
  ip_hash;
  server localhost:8001;
  server localhost:8002;
}

Remarks:

  • Before nginx version 1.3.1, weight cannot be used in ip_hash.
  • ip_hash cannot be used with backup.
  • This policy is appropriate for stateful services such as session.
  • When a server needs to be removed, it must be manually down loaded.

(4) least_conn

Represents forwarding requests to back-end servers with fewer connections. Polling algorithms average requests to each backend so that their load is roughly the same; however, some requests take a long time, resulting in higher backend load. In this case, least_conn can achieve better load balancing effect.

upstream my_server {
  least_conn;
  server localhost:8001;
  server localhost:8002;
}

(5) down

Represents that the current server is temporarily not involved in load balancing.

upstream my_server {
  server localhost:8001 down;
  server localhost:8002;
  server localhost:8003;
}

(6) backup

Represents a reserved backup machine. When all other non-backup machines fail or are busy, the backup machine will be requested, so the pressure on this machine is the least.

upstream my_server {
  server localhost:8001 backup;
  server localhost:8002;
  server localhost:8003;
}

Topics: Web Server Nginx Session SSL