Summary of Nginx Basic knowledge

Source: Internet
Author: User
Tags md5 sendfile tomcat nginx load balancing

The configuration file explains:

#user nobody;

#开启进程数 <= CPU number 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 {#使用网络IO模型linux建议epoll, FreeBSD recommends using Kqueue,window not specified. 

	#use Epoll;
#每个进程最大连接数 (max connections = number of connections * processes) worker_connections 1024;
	
	HTTP {#文件扩展名与文件类型映射表 include mime.types;

	#默认文件类型 Default_type Application/octet-stream;                  #日志文件输出格式 (this position is equivalent to the global setting) #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; #开启高效文件传输模式, the sendfile instruction specifies whether Nginx calls the Sendfile function to output the file, and for normal applications to be set to ON, if it is used for downloading applications such as disk IO heavy load applications, can be off to balance disk and network I/O processing speed, Reduce the load on the system.
    Note: If the picture does not appear normal, change this to off.
	#tcp_nopush on;
	
	Tcp_nodelay on; #禁止出错时泄露服务器的版本 Server_tokens Off
    #连接超时时间 #keepalive_timeout 0; Keepalive_timeout 65;
	#长连接超时时间, Unit is seconds client_header_timeout 3m;
	Client_body_timeout 3m;

	Send_timeout 3m;
	
	#打开gzip压缩 #gzip on; #设置允许压缩的页面最小字节数, the number of page bytes is obtained from Content-length in header. The default value is 0, regardless of the number of pages in most compression.
	It is recommended to set the number of bytes greater than 1k, which may be more or less larger than 1k.
	
	Gzip_min_length 1024; #设置系统获取几个单位的缓存用于存储gzip的压缩结果数据流. For example, 4 4k represents 4 times times the original data size in 4k, in 4k, for memory.
	4 8k represents 4 times times the original data size in 8k for the memory, in 8k units.
	
	Gzip_buffers 4 8K;
	#配置需要压缩的请求的Content the-type type to enable gzip compression for requests that meet the specified type.
	
	Gzip_types text/plain application/javascript text/xml text/css text/html application/xml;  
	#设定请求缓冲 Client_header_buffer_size 1k;

	Large_client_header_buffers 4 4k;
	
		#设定负载均衡的服务器集群 (MyProject is the name of the agent) upstream MyProject {#ip_hash; #weigth参数表示权值, the higher the weight, the greater the chance of being allocated #max_fails当有 #max_fails requests fail, which means that the backend server is unavailable, the default is 1, and setting it to 0 closes the check #fail_timeout在以后的 #fail_ Timeout time Nginx will no longer send the request to a server that has been marked as unavailable #这里指定多个源服务器, IP: port, 80 port can be written without writing server 192.168.1.78:8080 weight=5 max_fails=2 F ail_timeout=600s; 
		#server 192.168.1.222:8080 weight=3 max_fails=2 fail_timeout=600s;
		
		} #虚拟主机 Server {#监听ip端口 Listen 80; 
	
		#虚拟主机名 server_name localhost;

		#设置字符集 #charset Koi8-r;

		#本虚拟server的访问日志 is equivalent to a local variable #access_log logs/host.access.log main; #匹配请求路径 location/{root HTML; #定义服务器的默认网站根目录位置 index index.html index.htm; #定义首页索引文件的    
            Name Proxy_connect_timeout 3;    
			Proxy_send_timeout 30;
			
			Proxy_read_timeout 30; #代理路径 equivalent to forwarding, does not point to nginx static file Proxy_pass http://myproject;  
			#请求转向myproject定义的服务器列表 #以下是一些反向代理的配置可删除.
			
			# proxy_redirect off;
			
			#保留客户端请求的域名信息 # Proxy_set_header Host $host;
			
			#保留客户端请求的真实IP地址, used for some access statistics # Proxy_set_header X-real-ip $remote _addr;
			
			#带上客户原始请求IP等请求信息 # Proxy_set_header x-forwarded-for $proxy _add_x_forwarded_for; # client_max_body_size 10m; #允许客户端请求的最大单文件字节数 # client_body_buffer_size 128k; #缓冲区代理缓冲用户Maximum number of bytes requested by the end, # Proxy_connect_timeout 90; #nginx跟后端服务器连接超时时间 (proxy connection timeout) # Proxy_send_timeout 90; #后端服务器数据回传时间 (proxy send timeout) # Proxy_read_timeout 90; #连接成功后, back-end server response time (proxy receive timeout) # Proxy_buffer_size 4k; #设置代理服务器 (nginx) buffer size for saving user header information # proxy_buffers 4 32k; #proxy_buffers缓冲区, the average page below 32k, so set # Proxy_busy_buffers_size 64k; #高负荷下缓冲大小 (proxy_buffers*2) # proxy_temp_file_write_size 64k;   
		#设定缓存文件夹大小, greater than this value, will be passed from the upstream server} location/upload {alias e:/upload;   
			} #设定查看Nginx状态的地址 location/nginxstatus {stub_status on;   
			Access_log off;  
			#allow 192.168.0.3;  
			#deny all;   
			#auth_basic "Nginxstatus";   
		#auth_basic_user_file conf/htpasswd;

        } #error_page 404/404.html;
        # REDIRECT Server error pages to the static page/50x.html # Error_page 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 {# l
    Isten 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; #    }
    #}

}

Windows Nginx Operation instructions
--Starting the start Nginx
--Close Nginx-s stop
--Quit Nginx-s quit
--Restart Nginx-s reload
--Check Configuration Nginx-t


Let Nginx forward, the so-called reverse proxy. But in fact our needs will not be so, we need to sub-file types to filter, such as JSP directly to Tomcat processing, because Nginx is not a servlet container, no way to handle JSP, and html,js,css these do not need to deal with, directly to Nginx cache.
Next, let's configure the JSP page directly to Tomcat, and html,png and so on some pictures and JS and so on directly to the Nginx cache.
At this point the most important is the location of this element, and involves a part of the regular, but not difficult:


Location ~ \.jsp$ {
        proxy_pass http://localhost:8080;
}
		
Location ~ \. (html|js|css|png|gif) $ {
	root d:/software/developertools/server/apache-tomcat-7.0.8/webapps/root;
}

Remove the previous location/to avoid all requests being intercepted.

Load Balancing

Upstream Local_tomcat {
	server localhost:8080;
}

server{location
        /{
           proxy_pass http://local_tomcat;
        }
        #...... Other ellipsis
}

A upstream is added outside the server, and the name of the Http://+upstream is directly inside the proxy_pass.


Nginx Load Balancing Strategy

1. Polling (default)
Each Web request is assigned to a different back-end server in chronological order, and can be automatically rejected if the backend server is down.
2. Minimum link
Web requests are forwarded to the server with the fewest number of connections.
2.weight weights
Specifies the polling probability, which is proportional to the weight and the access ratio, and is used in cases where the performance of the backend server is uneven, and weight defaults to 1.
3.ip_hash
Each request is allocated according to the hash value of the IP access, so that the same client continuous Web requests are distributed to the same server for processing, which resolves the session problem. When the backend server goes down, it automatically jumps to the other server.
Weight-based load balancing and Ip_hash-based load balancing can be combined.


Configuring the static file time-out time

Location ~/wcm/*\. (Jpg|css|html|htm|js|gif|txt) { 
    root/home/trs/wchg/wwwhome/; 
    Expires 24h;
}

Specific syntax: Expires [TIME|EPOCH|MAX|PFF]
Default value: Off
Time: You can use a positive or negative number. The value of the "Expires" header will be set by the current system time plus the set value.
The time value also controls the value of "Cache-control":
Negative numbers indicate No-cache
Positive or zero indicates max-age=time


Application Examples:

#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_sen

    T "$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;  
	Upstream Local_tomcat {server 127.0.0.1:8080;
        } server {Listen 80; 

        server_name localhost;

        #charset Koi8-r;
		
		#access_log Logs/host.access.log Main;
			Location ~ (\.htm) $ {proxy_pass http://local_tomcat;
			Proxy_redirect off;
			Proxy_set_header Host $host; Proxy_Set_header X-real-ip $remote _addr;  
			Proxy_set_header x-forwarded-for $proxy _add_x_forwarded_for;
			Client_max_body_size 10m;
			Client_body_buffer_size 128k;
			Proxy_connect_timeout 90;
			Proxy_send_timeout 90;
			Proxy_read_timeout 90;
			Proxy_buffer_size 4k;
			Proxy_buffers 4 32k;
			Proxy_busy_buffers_size 64k;
		Proxy_temp_file_write_size 64k;
            } location/{root Html/pro_haopin;
			Index index.html index.htm;
        #proxy_pass Http://local_tomcat;

        } #error_page 404/404.html;
        # REDIRECT Server error pages to the static page/50x.html # Error_page 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 {# l
    Isten 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; #    }
    #}

}

Note: The parameters of the agent configuration should be noted

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.