Nginx load balancing configuration

Nginx’s upstream currently supports four modes of allocation

1. Polling (default)

Each request is allocated to a different backend server one by one in chronological order. If the backend server goes down, the request is automatically removed.

upstream nginx {
  server 172.17.0.4:8081;
  server 172.17.0.5:8081;
}
Copy the code

2, weight

Specifies the polling probability, weight proportional to the access ratio, for cases where back-end server performance is uneven. Down does not participate in the load temporarily

upstream nginx {
	server 172.17.0.4:8081 weight=2;
	server 172.17.0.5:8081 weight=1;
}
Copy the code

3, ip_hash

Each request is allocated according to the hash result of the access IP, so that each visitor has a fixed access to the back-end server, which can solve the session problem.

upstream nginx {
  ip_hash;
  server 172.17.0.4:8081;
  server 172.17.0.5:8081;
}
Copy the code

Nginx reverse proxy

There are now 4 servers, as follows

  1. 172.17.0.2 as the proxy nginx
  2. 172.17.0.3 Serves as a static server and reads HTML files
  3. 172.17.0.4 is background server 1 and provides Web services
  4. 172.17.0.5 is background server 2 and provides Web services

Configuration is as follows

upstream nginx {
# ip_hash;
server 172.17.0.4:8081 weight=2;
server 172.17.0.5:8081 weight=1;
}
server {
        listen       80;
        server_name  www.enjoy.com;
       
        location /proxy {
                proxy_pass http://172.17.0.4:8081/nginx/;
        }
        location /nginx {
                proxy_pass http://nginx;
        }
  				
        location /static{
    			proxy_pass http://static.enjoy.com/;
        }
  			
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            roothtml; }}Copy the code

Browser cross with issues

For the first time, Chrome uses the domain name Static.enjoy.com to load the HTML page ——-> and then make an Ajax request to the domain name www.enjoy.com.

Here’s the problem: Chrome rejects the return value from executing the Ajax request

Common cross-domain solutions:

Jsonp, document.domain + iframe cross domain

Cors solutions

Add header: access-Control-allow-origin to Allow the site to execute

CORS is a W3C standard, which stands for “Cross-origin Resource Sharing”. It allows browsers to make XMLHttpRequest requests across source servers, overcoming the limitation that AJAX can only be used in the same source. There are two intended processes for requests

  • If chrome finds an Ajax request url that is inconsistent with the current primary domain name (cross-domain), it appends the primary domain name value to the request header. Origin = static.enjoy.com

  • When nginx receives an Ajax request, it looks at the origin value, asking who is my URL? If I return information from enjoy.com, nginx appends the header value: Access-control-allow-origin = static.enjoy.com

    upstream nginx { ip_hash; Server 172.17.0.4:8081 weight = 2; Server 172.17.0.5:8081 weight = 1; } server { listen 80; server_name www.enjoy.com; if ( $http_origin ~ http://(.*).enjoy.com){ set $allow_url $http_origin; } # whether requests with authentication information are allowed add_header access-control-allow-credentials true; Add_header access-Control-allow-origin $allow_url; add_header access-control-allow-origin $allow_url Add_header access-control-allow-headers 'x-requested-with,content-type,Cache-Control,Pragma,Date,x-timestamp'; # allows you to use the request method, by commas add_header Access - Control - Allow - the Methods' POST, GET, OPTIONS, PUT, DELETE '; Add_header access-Control-expose-headers' www-authenticate, server-authorization '; Add_header P3P 'policyref="/w3c/p3p. XML ", CP="NOI DSP PSAa OUR BUS IND ONL UNI COM NAV INT LOC"'; add_header test 1; if ($request_method = 'OPTIONS') { return 204; } location / { root html/static/; index index.html index.htm; } location /rout { rewrite ^/rout/(.*) /static/$1.html break; root html/; index index.html index.htm; } location /proxy {echo "I am www.enjoy.com content :$http_origin"; # proxy_pass http://172.17.0.4:8081/nginx; } location /nginx { proxy_pass http://nginx; } error_page 500 502 503 504 /50x.html; location = /50x.html { root html; }}Copy the code
  • After receiving the Ajax value, Chrome checks the access-Control-allow-origin value in the header and finds the host name static.enjoy.com. This is allowed to access and then perform ajax return value content. Access-control-allow-origin: access-Control-allow-origin: access-Control-allow-origin: access-Control-allow-origin: access-Control-allow-origin

Cache configuration and Gzip configuration

The output to the client is compressed to reduce the volume of transmitted files and the occupation of network bandwidth.

For the server side to compress, the client side must uncompress, which takes up CPU time.

However, due to the reduced transmission content, network adapters, routers, and switches take shorter time to process data packets during transmission.

This is where gzip compression buys time.

The following conditions must be met:

  • The HTTP header sent by the client must contain the accept-Encoding field and its value must contain the compression type gzip. Browsers usually send “accept-encoding :gzip, deflate, SDCH” headers.

  • The server has gzip compression enabled, so the response header contains Content-Encoding:gzip, which the client uses to determine whether the server is returning Content that is truly gZIP-compressed.

Gzip compression works very well for text files (40 to 80 percent) and very little for image files. In practical applications, you can enable GZIP compression for FILES in JS, HTML, and CSS formats.

server {
        listen       80;
        server_name  static.enjoy.com;
	
        location / {
            root   html/static;
            index  index.html index.htm;
        }
        location^ ~ /cors {
                  alias   html/cors;
                  index  cors.html;
              }
        location ~ /(.*)\.(html|js|css|jpg|jpeg|png|gif)$ {Override the /re/a.htm path
          gzip on; # Enable gzip compression. Default is off

          # Enable gzip compression for JS, CSS, JPG, PNG, GIF files
          gzip_types application/javascript text/css image/jpeg image/png image/gif;
          gzip_min_length 1024; # The minimum value of the file to be compressed, less than this will not be compressed
          gzip_buffers 4 1k; # set the size and number of buffer blocks for compressed responses. Default is the size of a page
          gzip_comp_level 1; # Compression level, default 1. The value ranges from 1 to 9. A larger value increases the compression ratio but consumes more CPU time

          root html/gzip;
        }
        location^ ~ /qq.png {
        # expires 2s; Cache for 2 seconds
          expires 2m;# Cache for 2 minutes
        # expires 2h; # Cache for 2 hours
        # expires 2d; Cache for 2 days
          root html/gzip;
        }
        location^ ~ /chrome.png {
                      expires 2m;# Cache for 2 minutes
                      root html/gzip;
              }
  			# hotlinking prevention
        location^ ~ /mall {
          valid_referers *.enjoy.com;
              if ($invalid_referer) {
                return 404;
              }
          roothtml/gzip; }}Copy the code

Preventing hotlinking

Objective:

1. Make resources appear only on my page

2. It cannot be picked up or downloaded separately

Process:

Chrome first requests the Web server with URL1 and gets the HTML page.

2. Chrome re-initiates the URL2 resource request with referers = URL1. (Note, urL1, not urL2)

3. Nginx verifies the referers value to decide whether to allow access.

4. The following is the process of nginx verifying the referers value:

Valid_referers: Matches the whitelist of domain names. If not, set the built-in variable $inVALID_referers to 1, enter the if block, and return 404

	location^ ~ /mall {
		valid_referers *.enjoy.com;
    		if ($invalid_referer) {
    			return 404;
    		}
                root html/gzip;
   }
Copy the code

Configure HTTPS

The HTTPS process is shown in the figure above.

Public key and private key concepts

We generally buy a certificate will have three files, a password, a public key, a private key

The configuration is as follows:

server { listen 80; server_name sales.enjoy.com; // rewrite ^/ https://sales.enjoy.com redirect; Allow cross-domain location / { root html/sales; index welcome.html; } error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } } server { listen 443 ssl; server_name sales.enjoy.com; ssl_certificate /etc/nginx/conf.d/server.crt; Ssl_certificate_key /etc/nginx/conf.d/server_nopass.key; If ($http_origin ~ http://(.*).enjoy.com){set $allow_url $http_origin; } # allow cross-domain #... location / { root html/sales; index welcome.html; } error_page 500 502 503 504 /50x.html; location = /50x.html { root html; }}Copy the code

keepalived

It is used to configure nginx high availability, which is basically not used by anyone, and I won’t go into that because we have a domain name that is resolved across domains to multiple servers which is itself high availability. And there are only two Keepaliver.