Juejin. Cn/post / 684490…

What is the Nginx?

Nginx is a free and open source high-performance HTTP server and Reverse Proxy that can provide IMAP/POP3/SMATP Proxy services. Can quickly respond to static page requests and support third party function module expansion.

The advantages of Nginx

  • High concurrency and high performance (the official number of concurrent data is 50,000, but the actual number can reach 20,000-40,000)
  • Lightweight, low memory consumption
  • High stability and low downtime probability
  • Hot deployment
  • Modular design, good expansibility
  • CPU affinity

Common scenarios for Nginx

  • Static resource server
  • Dynamic matching
  • The reverse proxy
  • Gzip compression
  • Load balancing

Nginx installation configuration

Detailed installation tutorial can refer to this article www.zhuxiaodong.net/2016/config…

Nginx common commands

  • Viewing the Version Number
nginx  -v 
Copy the code
  • View parameters for nginx compilation
nginx -V
Copy the code
  • Gracefully reboot and reload the configuration file nginx.conf
/usr/local/nginx/sbin/nginx  -s  reload
Copy the code
  • Gracefully stop nginx and wait for connection requests to complete before killing worker processes
/usr/local/nginx/sbin/nginx  -s  quit
Copy the code

Common commands are as follows:

Nginx -s stop Quickly shuts down nginx, possibly without saving the information, and quickly terminates the Web service. Nginx -s quit Smoothly shut down nginx, save the information, and end the Web service on schedule. Nginx-s reload is reloaded because the nginx-related configuration has been changed and needs to be reloaded. Nginx -s reopen the log file. Nginx -c filename Specifies a configuration file for nginx instead of the default. Nginx -t does not run, only tests configuration files. Nginx checks the syntax of the configuration file and tries to open the file referenced in the configuration file. Nginx -v Displays the nginx version. Nginx -v displays the nginx version, compiler version, and configuration parameters.Copy the code

Note that there is no nginx -s start command in nginx

Sometimes when you run

/usr/local/nginx/sbin/nginx -s  stop
Copy the code

An error:

/usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
Copy the code

Can solve this problem.

Default configuration for Nginx

Nginx. conf is the Nginx global configuration file in the Nginx installation directory. Nginx.conf. default is used as a backup of the configuration file.

The configuration information in nginx.conf is as follows:


#user nobody;
#Set the number of worker processes
worker_processes  1;

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

#pid logs/nginx.pid;

#Deal with connection
events {
	#Setting the number of connections
    worker_connections  1024;
}


http {
	#File extension lookup collectioninclude mime.types; Default_type application/octet-stream;	#Log format, alias main by definition#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;	
	#Call the sendFile system to transfer the file
    sendfile        on;
    #tcp_nopush     on;
	
	#The connection between the client and the server times out
    #keepalive_timeout  0;
    keepalive_timeout  65;

	#Enable Gizip compression
    #gzip  on;

	#Virtual host
    server {
        listen       8081;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

		#routinglocation / { 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 9090; Server_name 127.0.0.1; location / { root build; 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

Setting up a Static site

#Virtual host server blockServer {# port listen 8080; Server_name localhost; Location / {# root /source; HTML index.htm; }}Copy the code

Here are the related fields:

  • Server Configures multiple virtual host parameters
  • Server_name Finds the configuration of the corresponding virtual host based on the host value in the request
  • Location Configures request routes and processes related pages
  • Root Searches the path of the resource

After the configuration is complete, run nginx -t to see if there are any errors

nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
Copy the code

Then execute nginx -s reload to update the nginx configuration file, open the browser, type localhost:8080, and you should see your page.

Dynamic matching (request filtering)

Usually in the development environment or in the test environment we change the code, because the browser cache might not work, and you have to clear the cache manually to see what happens, so let’s make a configuration so that the browser doesn’t cache the relevant resources.

location ~* \.(js|css|png|jpg|gif)$ {
    add_header Cache-Control no-store;
}
Copy the code

~ *. (js | | CSS PNG | JPG | GIF) $is matched with relevant document type and then separate processing. Cache-control no-store specifies whether to disable caching in the browser. The add_header header specifies whether to disable caching in the browser.

location = / {
    [ configuration A ]
}

location / {
    [ configuration B ]
}

location /documents/ {
    [ configuration C ]
}

location ^~ /images/ {
    [ configuration D ]
}

location ~* \.(gif|jpg|jpeg)$ {
    [ configuration E ]
}
Copy the code
Location = | | | ~ ~ * ^ ~ | / uri /
  • = indicates an exact match. Hit only if the requested URL path is exactly the same as the following string (highest priority).
  • ^~ indicates that if the character following the symbol is the best match, this rule is adopted and no further search is performed.
  • ~ indicates that the rule is case sensitive and is defined using re.
  • ~* indicates that the rule is defined using re and is case insensitive.
  • / universal match. Any request will be matched

Conclusion:

  1. Check for accurate hit. If yes, return the result immediately and end the parsing process
  2. Judge common hits. If there are multiple hits, record the longest hit result
  3. If a hit begins with ^~, the search for regular hits does not continue, but for general hits
  4. Determine the result of regular expression parsing and match the result from top to bottom based on the sequence specified in the configuration. If a match is successful, the result is returned immediately and the parsing process is complete.
  5. Ordinary hit: order does not matter, because according to hit length to determine
  6. Regular hits: Order is important because they are made from front to back

Of course, we can also filter requests through status codes like this:

#Returns the specified error page through the status code
error_page 500 502 503 504 /50x.html;
location = /50x.html {
    root /source/error_page;
}
Copy the code

Reverse proxy resolves cross-domain

Mention cross-domain issues and the concept of the same origin policy is introduced. The same origin policy is a mechanism in browsers and JavaScript does not allow cross-domain calls to objects on other pages due to security concerns. What is homology? To put it simply:

The domain name, port number, and protocol are all the same. If one of the three is different, the policy does not comply with the same origin policy, and cross-domain is generated.

In the development of front-end and back-end separation, cross-domain problem is a very common problem. Now there are two commonly used ways to solve cross-domain problem:

  • Cross-domain Resource Request (CORS)
  • Nginx echo agent

xx.720ui.com/server1

At the same time, nginx addresses the configuration of parameters commonly used across domains.

Proxy_set_header host $http_host; Proxy_set_header x-real-ip $remote_addr; Proxy_set_header X -scheme $Scheme; Rewrite/API /(.*) /$1 break; Proxy_pass http://localhost:9000; }Copy the code
  • Intercepting paths/apis, which can be matched by re
  • Proxy_set_header allows you to redefine or add request headers that fields pass to the proxy server
  • Remote_addr and $scheme are Nginx built-in variables
  • Rewrite: / API /user: / API /user: / API /user: / API /user (Why do I need to rewrite the URI? This is because when you use Nginx as a reverse proxy, you need to rewrite a path (or flag, as in the API example) in the original interface to make it easy to match.
  • Break Continues with the request and stops matching the location below. Note that last, similarly, stops the current request and re-initiates a request based on the rewrite matching rules, matching the rules after location from top to bottom
  • Proxy_pass proxy server

Principle: Nginx intercepts the relevant matching rules, Nginx forwards the request to http://localhost:9000, Nginx gets the request and then responds to the front end, can directly request/API /user to complete the request.

Nginx cross-domain requests a simple dome:

server { listen 80; server_name www.1212.com; location ^~ /blog/ { proxy_pass http://blog.12121.com/; }}Copy the code

Configuring Gzip

In the development process, it is inevitable to use some mature frameworks or plug-ins. These external dependencies are sometimes large, resulting in slow page response. We can use packaging tools (Webpack, rollup) to compress the code to reduce the code volume. Enable the Nginx Gzip compression function. It is important to note that the Gzip compression function needs to be supported by both the browser and the server, that is, server compression, browser parsing.

  • Check browser support to determine the Accept-Encoding field in the request header
  • Make sure the browser supports it and we can configure it in Nginx
Server {# enable gzip on; Gzip_http_version 1.1 (HTTP/1.1, HTTP/1.0); The higher the compression level, the longer the compression time (1-9). Content-length = gzip_min_length 1000; Gzip_types text/plain Application /javascript text/ CSS; }Copy the code
  • To check whether the configuration takes effect, view the Content-Encoding field in the response header with the value of gzip

Load balancing

Load balancing is a common feature of Nginx to optimize resource utilization, maximize throughput, reduce latency, ensure fault-tolerant configuration, and distribute traffic to multiple back-end servers

Several common strategies:

  • Polling (default), Nginx randomly allocates traffic to any server when the request comes in
Upstream Backend {server 127.0.0.1:3000; Server 127.0.0.1:3001; }Copy the code
  • Weight =number Specifies the weight of the server. The default value is 1
Upstream Backend {server 127.0.0.1:3000 weight=2; Server 127.0.0.1:3001 weight = 1; }Copy the code
  • Backup indicates the backup server. When the primary server is unavailable, the connection to the backup server is passed
Upstream Backend {server 127.0.0.1:3000 backup; Server 127.0.0.1:3001; }Copy the code
  • Ip_hash keeps sessions to ensure that the same client always accesses the same server
upstream backend { ip_hash; 3000 backup server 127.0.0.1:; Server 127.0.0.1:3001; }Copy the code
  • Least_conn prioritizes the server with the least number of connections to avoid server overload
upstream backend {
    least_conn;
    server 127.0.0.1:3000;
    server 127.0.0.1:3001;
}
Copy the code

When we need to broker a cluster we can do this

HTTP {upstream Backend {server 127.0.0.1:3000; Server 127.0.0.1:3001; }... server { listen 9000; server_name localhost; location / { proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Scheme $scheme; proxy_pass backend; }}}Copy the code