1. The Nginx is introduced

  • Nginx is a lightweight Web/reverse proxy server and E-mail (IMAP/POP3) proxy server distributed under a BSD-like protocol. Developed by Igor Sysoev, a Russian programmer, for use by Rambler(р а блер), a large Russian portal and search engine. It is characterized by less memory, strong concurrency,

  • Nginx is a high-performance Web and reverse proxy server with a number of very good features:

As a Web server: Nginx uses fewer resources, supports more concurrent connections, and is more efficient than Apache, which makes Nginx especially popular with Web hosting providers. Can support responses up to 50,000 concurrent connections, thanks to Nginx for choosing epoll and KQueue as our development models.

  • As a load balancer: Nginx can support Rails and PHP directly internally or as an HTTP proxy server externally. Written in C, Nginx is much more efficient in both system resource overhead and CPU usage than Perlbal.

  • Nginx general user layer 7 load balancing, its throughput has certain limitations. In order to improve the overall throughput, LVS(software load balancer) and F5 (hard load balancer) will be introduced between DNS and Nginx to perform four-layer load balancing. First, DNS resolves to LVS(F5), then LVS(F5) forwards to Nginx, and Nginx forwards to real servers

2. Install Nginx on Linux

  1. Installing dependency packages
yum -y install gcc zlib zlib-devel pcre-devel openssl openssl-devel
Copy the code
  1. Download the unzip nginx installation package
// Create a foldercd /usr/local
mkdir nginx
cdNginx // Download tar packagewget http://nginx.org/download/nginx- 1.6.3.tar.gz
tar -xvf nginx- 1.6.3.tar.gz
Copy the code
  1. Install nginx
// Access the nginx directorycd/usr/local/nginx // To access the directorycd nginx- 1.6.3/configure // Run the make command make // Run the make install command make installCopy the code
  1. Start the nginx
/usr/local/nginx/sbin/nginx -s reload
Copy the code

If there is an error: nginx: [error] open () “/ usr/local/nginx/logs/nginx pid” failed

Run: / usr/local/nginx/sbin/nginx – c/usr/local/nginx/conf/nginx. Conf

3. Nginx application scenarios

  1. HTTP server. Nginx is an HTTP service that can provide HTTP services independently. Can do web static server.
  2. Virtual hosting. Multiple websites can be created on one server, for example, virtual machines for personal websites.
  3. Reverse proxy, load balancer. When the number of visits to the website reaches a certain level, a single server cannot meet the user’s request, you need to use multiple server cluster can use Nginx as a reverse proxy. In addition, multiple servers can share the load equally, so that one server will not be idle due to the high load of a server downtime.
  4. Nginz can also configure security management, for example, you can use Nginx to build API interface gateway, the interception of each interface service.

4. Nginx directory structure

Run tree /application/nginx; Yum install tree -y yum install tree -y

 yum install tree -y
Copy the code
[root@vm10-0-0-128 local]# tree nginx/Nginx / ├─ client_body_temp ├─ conf# this is the directory for all configuration files of Nginx, extremely important│ ├ ─ ─ fastcgi. Conf#fastcgi configuration file for related parameters│ ├ ─ ─ fastcgi. Conf. Default#fastcgi.conf original backup│ ├─ FastCGI_Flag │ ├─ FastCGI_Flag. Default │ ├─ KoI-utf│ ├ ─ ─ koi-win│ ├─ Mime.types │ ├─ mime.types. Default │ ├─ Nginx.confThis is the default main configuration file for Nginx│ ├ ─ ─ nginx. Conf. Default │ ├ ─ ─ scgi_params │ ├ ─ ─ scgi_params. Default │ ├ ─ ─ uwsgi_params │ ├ ─ ─ uwsgi_params. Default │ └ ─ ─  win-utf├ ─ ─ fastcgi_temp#fastcgi temporary data directory├ ─ ─ HTML# this is the default Nginx site directory for compiling and installing Nginx│ ├ ─ ─50├─ ├─ exercisesThis is the default Nginx log path, including error logs and access logs│ ├ ─ ─ the access log# This is the default access log file for Nginx. Use tail -f access.log to view real-time information about website users│ ├ ─ ─ the error log# This is the error log file for Nginx. If Nginx has startup problems, be sure to see this error log│ └ ─ ─ nginx. Pid#Nginx pid file. After the Nginx process is started, all process ids are written to this file├ ─ ─ proxy_temp# temporary directory├ ─ ─ sbin# this is the directory for Nginx commands, such as Nginx startup command Nginx│ ├─ Nginx ├─ scgi_temp# temporary directory└ ─ ─ uwsgi_temp# temporary directory


Copy the code

5. Nginx main configuration file nginx.conf

#user nobody; # define users and user groups to run Nginx
worker_processes  1;                 # Number of nginx processes. It is recommended that the value be set to the total number of CPU cores.
#error_log logs/error.log; Global error log definition type,
#error_log logs/error.log notice; # process file
#error_log logs/error.log info;

#pid logs/nginx.pid;


events {
    worker_connections  1024;       # Maximum number of connections per process (maximum number of connections = number of connections * number of processes)
}

 #HTTP block start core area
http {
    include       mime.types;        #Nginx supports media type library files
    default_type  application/octet-stream;   The default media type
    # client_header_buffer_size 32 k; # Upload file size limit
    large_client_header_buffers 4 64k;Set the request cache value

    sendfile        on;   Enable efficient file transfer mode, s
    #tcp_nopush on; Prevent network congestion
    # tcp_nodelay on; Prevent network congestion

    #keepalive_timeout 0;
    keepalive_timeout  65;    Connection timed out in seconds

	#FastCGI parameters are designed to improve the performance of your site: reduce resource usage and increase access speed.
	fastcgi_connect_timeout 300;
	fastcgi_send_timeout 300;
	fastcgi_read_timeout 300;
	fastcgi_buffer_size 64k;
	fastcgi_buffers 4 64k;
	fastcgi_busy_buffers_size 128k;
	fastcgi_temp_file_write_size 128k;

	# Gzip module Settings
    #gzip on; # Enable gzip compressed output
 
	# Virtual host configuration
    server {
        listen       8080;         # monitor port
        server_name  localhost;    The host name is the domain name of the service
        
  # location
  The function of the # location directive is to perform different applications according to the URI requested by the user, that is, to match the website URL requested by the user, once the match succeeds, relevant operations will be performed.
  # 1. = Indicates an exact match
  # 2. ^~ indicates that the URI begins with some regular string
  # 3. ~ indicates case-sensitive regular matching;
  The beginning of # 4. ~* indicates case-insensitive regular matching
  # 5. / Universal match, if there is no other match, any request will be matched

        location /{               # reverse proxy for /
            root   html;           # the root directory of the site
            index  index.html index.htm;       # Default home page file
			try_files $uri $uri/ /index.html;
			proxy_set_header X-Real-IP $remote_addr;The backend Web server can obtain the real IP address of the user through x-Forwarded-For
			# Here are some optional reverse proxy configurations
		    proxy_set_header Host $host;
		    client_max_body_size 10m;# Maximum number of bytes per file that a client can request
		    client_body_buffer_size 128k;The buffer agent can buffer the maximum number of bytes requested by the client.
		    proxy_connect_timeout 90;#nginx connection timeout (proxy connection timeout)
			proxy_send_timeout 90;# backend server data return time (proxy send timeout)
			proxy_read_timeout 90;Backend server response time after successful connection (proxy receive timeout)
			proxy_buffer_size 4k;Set the buffer size for the proxy server (nginx) to hold user headers
			proxy_buffers 4 32k;#proxy_buffers buffer, page average set below 32K
			proxy_busy_buffers_size 64k;# Buffers for high load (proxy_buffers*2)
			proxy_temp_file_write_size 64k;   Set the cache folder size to upstream if it is larger than this
        }
		location  /i5n/ {
            proxy_pass http://127.0.0.1:8080/i5n/;
		}

        #error_page 404 /404.html;

        # redirect server error pages to the static page /50x.html
        #
        Error pages can be customized to their own pages
        error_page   500 502 503 504  /50x.html;
        location = /50x.html { root html; }}Copy the code

6. Configure the domain name based on the virtual host

    If the client accesses www.yanxiaolong.cn and listens on port 80, jump directly to the files in the data/ WWW directory
    server {
        listen       80;
        server_name  www.yanxiaolong.cn;
        location / {
            root   data/www; index index.html index.htm; }}Yanxiaolu.cn, listening port 80, jump to data/blow directory
	 server {
        listen       80;
        server_name  blog.itmayiedu.com;
        location / {
            root   data/blog; index index.html index.htm; }}Copy the code

7. Configure the domain name based on the virtual host

If the client accesses www.yanxiaolong.cn and listens on port 8080, jump directly to the files in the data/ WWW directory
	 server {
        listen       8080;
        server_name  www.yanxiaolong.cn;
        location / {
            root   data/www; index index.html index.htm; }}Yanxiaolu.cn, listening port 8081, jump directly to data/blog directory file
	 server {
        listen       8081;
        server_name  blog.yanxiaolong.cn;
        location / {
            root   data/blog; index index.html index.htm; }}Copy the code

8. Configure the reverse proxy on Nginx

  • In Reverse Proxy mode, a Proxy server receives Internet connection requests, forwards the requests to the Intranet server, and returns the results to the Internet client. In this case, the proxy server acts as a reverse proxy server.

  • The advantage of reverse proxy is to hide the real internal IP address, request first access to the Nginx proxy server (the external network can access), then use the Nginx server to forward to the real server.

Configuration:

# when the client accesses api.yanxiaolu.cn and listens on port 80 jump directly to the real IP server address 127.0.0.1:8080
	server {
        listen       80;
        server_name  api.yanxiaolong.cn;
        location / {
		   proxy_pass http://127.0.0.1:8080; }}# when the client accesses api2.yanxiaolu.cn, listening port 80 directly jumps to the real IP server address 127.0.0.1:8081
	server {
        listen       80;
        server_name  api2.yanxiaolong.cn;
        location / {
		    proxy_pass http://127.0.0.1:8081; }}Copy the code

9. Nginx configures load balancing

  • Nginx load balancing provides upstream servers (servers accessed by real business logic), load balancing, failover, failure retries, fault tolerance, health check, and more.
  • When the upstream server (the server accessed by real business logic) fails, it can be moved to another upstream server (the server accessed by real business logic).

Load balancing algorithm

  1. Polling (default)

Each request is allocated to a different back-end service one by one in chronological order. If a back-end server crashes, the faulty system is automatically removed, so that users’ access is not affected. 2. Weight (polling weight) The larger the weight value is, the higher the access probability is, which is mainly used when the performance of each back-end server is unbalanced. Or just set different weights in the case of master and slave to achieve reasonable and effective use of host resources. 3. Ip_hash Assigns each request based on the hash result of the access IP address, so that visitors from the same IP address can access the same back-end server, and effectively solve the session sharing problem existing in dynamic web pages. Commonly known as IP binding.

  1. Fair (third party) needs to use external extension load balancing algorithm that is smarter than weight and IP_hash. Fair algorithm can perform load balancing intelligently based on page size and load time. That is, it allocates requests based on the response time of the back-end server. Nginx does not support fair itself, so if you want this scheduling algorithm, you must install the upstream_fair module.

  2. Url_hash (third-party) requires an external extension to allocate requests based on the hash result of the URL accessed, directing each URL to a back-end server, further improving the efficiency of the back-end cache server. Nginx does not support URl_hash. If this scheduling algorithm is required, you must install the Nginx Hash software package.

Polling:

upstream  backServer{
	server 127.0.0.1:8080;  
	server 127.0.0.1:8081;
	}
 	
	server {
        listen       80;
        server_name  api.yanxiaolong.cn;
        location / {
		# specify upstream server load balancing serverproxy_pass http://backServer; }}Copy the code

Weighted polling:

upstream  backServer{
	server 127.0.0.1:8080 wight = 1;  
	server 127.0.0.1:8081 wight = 2;
	}
 	
	server {
        listen       80;
        server_name  api.yanxiaolong.cn;
        location / {
		# specify upstream server load balancing serverproxy_pass http://backServer; }}Copy the code

The IP ip_hash

upstream  backServer{
	    server 127.0.0.1:8080 ;
		server 192.168.10.225:8081 max_fails=3 fail_timeout=15;
		ip_hash; 
	}
 	
	server {
        listen       80;
        server_name  api.yanxiaolong.cn;
        location / {
		    # specify upstream server load balancing serverproxy_pass http://backServer; }}Copy the code

10. Nginx configure failover

  • If the upstream server (real access server) fails or does not respond in time, it should be directly rotated to the next server to ensure high availability of the server.
upstream  backServer{
	server 127.0.0.1:8080 wight = 1;  
	server 127.0.0.1:8081 wight = 2;
	}

server {
        listen       80;
        server_name  www.itmayiedu.com;
        location / {
		    ## specifies the upstream server load balancing server
		    proxy_pass http://backServer;
		    #nginx timeout with the upstream server (real access server) timeout with the backend server connection _ initiate handshake waiting response timeout
			proxy_connect_timeout 20s;
			#nginx sends timeout to upstream servers (real access servers)
            proxy_send_timeout 20s;
			### Nginx accepts upstream server (real access server) timeout
            proxy_read_timeout 20s; }}Copy the code

Rewrite: nginx rewrite

Nginx provides global variables or set variables, combined with regular expressions and flag bits to achieve URL rewriting and redirection. Rewrite can only be used in server{},location{},if{}, and only on strings after domain names, excluding passed arguments. Rewrite (Pcre) is the Rewrite rule in Nginx. Perl is compatible with regular expressions. With the Rewrite rules, it is possible to implement canonical urls, redirect urls based on variables, and select configurations.

Rewrite global variables:

variable instructions
$args Holds the request directive in the request URL. Such aswww.myweb.name/server/sour…
$content_length Holds the Content-Length field in the request header
$content_type Holds the Content-Type field in the request header
$document_root Holds the root path for the current request
$document_uri The URI in the request does not contain the request instruction, e.gwww.myweb.name/server/sour…
$host Holds the host field in the request URL, such aswww.myweb.name/server/sour…
$http_cookie cookie
$limit_rate The configuration value of the limit_rate directive in nginx configuration
$remote_addr Client Address
$remote_port Port number for the connection between the client and server
$remote_user The variable holds the user name of the client
$request_body_file The name of the local file resource that holds the file destined for the backend server
$request_method Store the client request mode, such as GET, POST, etc
$request_filename The path name of the resource file that holds the current request
$query_string $args has the same meaning
$scheme Protocol used for client requests, such as HTTP, HTTPS, and FTP
$server_protocol Client request protocol version, such as “HTTP/1.0”, “HTTP/1.1”
$server_addr Server address
$server_name The name of the server to which the client requests to arrive

Determine the source of the IP address


server {
      listen 80;
      server_name www.yanxiaolong,cn;
      location / {
        If it is not a whitelist, 403 is forbidden
       if  ($remote_addr = 192.168.5.166) {  
         return 403; }}Copy the code

Restrict browser access

server {
      listen 80;
      server_name www.yanxiaolong,cn;
      location / {
       ## Does not allow Chrome access if it is Chrome return 500
 	  if ($http_user_agent ~ Chrome) {   
         return 500; }}Copy the code

Nginx1.9 began to support TCP layer forwarding via stream

### change to TCP module
tcp {
   
   ### Define multiple upstream servers
   upstream  backServer{
      ### define TCP module upstream server
      server 192.168.5.165:80001;
	  server 192.168.5.165:80002;
   }
    server {
        listen       9999;
        server_name  api.yanxiaolong.cn;
		### Reverse proxy upstreamproxy_pass backServer; }}Copy the code

Personal blog address: blog.yanxiaolu.cn /