Nginx相关案例

以下案例均以编译安装为基础:

一、新建一个PC web站点:
[root@s2 ~]# mkdir /apps/nginx/conf/conf.d 
[root@s2 ~]# vim /apps/nginx/conf/conf.d/pc.conf 
server { 
	listen 80; 
	server_name www.a.net; 
	location / { 
		root /data/nginx/html/pc; 
	} 
}
include /apps/nginx/conf/conf.d/*.conf;
[root@s2 ~]# mkdir /data/nginx/html/pc -p 
[root@s2 ~]# echo "pc web" > /data/nginx/html/pc/index.html 
[root@s2 ~]# systemctl reload nginx 
访问测试
二、新建一个Mobile web站点:
[root@s2 ~]# vim /apps/nginx/conf/conf.d/mobile.conf 
server { 
	listen 80; 
	server_name mobile.a.net; 
	location / { 
		root /data/nginx/html/mobile; 
	} 
}
[root@s2 ~]# mkdir /data/nginx/html/mobile -p 
[root@s2 ~]# echo "mobile web" >> /data/nginx/html/mobile/index.html 
[root@s2 ~]# systemctl reload nginx
三、location生产使用案例:
#直接匹配网站根会加速Nginx访问处理: 
location = / { 
	......; 
}
#静态资源配置: 
location ^~ /static/ { 
	......; 
}
# 或者 
location ~* \.(gif|jpg|jpeg|png|css|js|ico)$ { 
	......; 
}
#多应用配置 
location ~* /app1 { 
	......; 
}
location ~* /app2 { 
	......; 
}
四、开启Nginx账户认证功能:
[root@s2 ~]# yum install httpd-tools -y 
[root@s2 ~]# htpasswd -cbm /apps/nginx/conf/.htpasswd user1 123456 
Adding password for user user1 
[root@s2 ~]# htpasswd -bm /apps/nginx/conf/.htpasswd user2 123456 
Adding password for user user2 
[root@s2 ~]# tail /apps/nginx/conf/.htpasswd 
user1:$apr1$Rjm0u2Kr$VHvkAIc5OYg.3ZoaGwaGq/ 
user2:$apr1$nIqnxoJB$LR9W1DTJT.viDJhXa6wHv. 
[root@s2 ~]# vim /apps/nginx/conf/conf.d/pc.conf 
location = /login/ { 
	root /data/nginx/html/pc; 
	index index.html; 
	auth_basic "login password"; 
	auth_basic_user_file /apps/nginx/conf/.htpasswd; 
} 
重启Nginx并访问测试
五、配置为下载服务器:
[root@s2 about]# mkdir /data/nginx/html/pc/download #download不需要index.html文件 
[root@s2 about]# vim /apps/nginx/conf/conf.d/pc.conf 
location /download { 
	root /data/nginx/html/pc; 
	autoindex on; #自动索引功能 
	autoindex_exact_size on; #计算文件确切大小(单位bytes),off只显示大概大小(单位kb、 mb、gb)
	autoindex_localtime on; #显示本机时间而非GMT(格林威治)时间 
	limit_rate 10k; #限制响应给客户端的传输速率,单位是bytes/second,默认值0表示无限制 限速与不限速的对比:
} 
[root@s2 pc]# cp /root/anaconda-ks.cfg /data/nginx/html/pc/download/ 
重启Nginx并访问测试下载页面
六、配置作为上传服务器:
[root@s3 ~]# md5sum /data/nginx/html/pc/index.html 
95f6f65f498c74938064851b1bb963d4 /data/nginx/html/pc/index.html 
1级目录占1位16进制,即2^4=16个目录 0-f 
2级目录占2位16进制,即2^8=256个目录 00-ff 
3级目录占2位16进制,即2^8=256个目录 00-ff 
配置示例:
[root@s2 about]# vim /apps/nginx/conf/conf.d/pc.conf 
location /upload { 
	root /data/nginx/html/pc; 
	index index.html;
#设置允许客户端上传单个文件的最大值,默认值为1m
	client_max_body_size 10m; 
#用于接收每个客户端请求报文的body部分的缓冲区大小;默认16k; 超出此大小时,其将被暂存到磁盘上的由下面client_body_temp_path指令所定义的位置
	client_body_buffer_size 16k; 
#设定存储客户端请求报文的body部分的临时存储路径及子目录结构和数量,目录名为16进制的数字,使用 hash之后的值从后往前截取1位、2位、2位作为文件名
	client_body_temp_path /apps/nginx/temp 1 2 2; #reload Nginx会自动创建temp目录
	limit_except GET { 
		allow 192.168.0.0/24; 
		allow 192.168.7.102; 
		deny all;
#重启Nginx并进行测试上传文件 

Nginx相关案例_第1张图片

七、第三方模块的使用

第三模块是对nginx 的功能扩展,第三方模块需要在编译安装Nginx 的时候使用参数–add-module=PATH指定路径添加

1、echo模块(基于模块echo-nginx-module)

官方文档:https://github.com/openr esty/echo-nginx-module

[root@s2 src]# yum install git -y 
[root@s2 src]# git clone https://github.com/openresty/echo-nginx-module.git #克隆远程版本库
[root@s2 src]# cd nginx-1.12.2/ 
[root@s2 src]# ./configure \ 
--prefix=/apps/nginx \ 
--user=nginx 
--group=nginx \ 
--with-http_ssl_module \ 
--with-http_v2_module \ 
--with-http_realip_module \ 
--with-http_stub_status_module \ 
--with-http_gzip_static_module \ 
--with-pcre \ --with-stream \ 
--with-stream_ssl_module \ 
--with-stream_realip_module \ 
--with-http_perl_module \ 
--add-module=/usr/local/src/echo-nginx-module 
[root@s2 src]# make && make install
[root@s2 pc]# vim /apps/nginx/conf/conf.d/pc.conf 
location /main { 
	index index.html; 
	default_type text/html; 
	echo "hello world,main-->"; 
	echo_reset_timer; 
	echo_location /sub1; 
	echo_location /sub2; 
	echo "took $echo_timer_elapsed sec for total."; 
}
location /sub1 { 
	echo_sleep 1; 
	echo sub1; }
location /sub2 { 
	echo_sleep 1; 
	echo sub2; 
}
#确认语法检测通过 
[root@s2 pc]# /apps/nginx/sbin/nginx -t 
nginx: the configuration file /apps/nginx/conf/nginx.conf syntax is ok 
nginx: configuration file /apps/nginx/conf/nginx.conf test is successful 
#重启nginx访问测试: 
[root@s2 pc]# systemctl restart nginx 
[root@s2 pc]# curl http://www.a.net/main 
hello world,main--> 
sub1 
sub2 
took 2.010 sec for total.
八、Nginx 自定义访问日志:

定义一个日志需要使用access_log指定日志的保存路径,使用log_format指定日志的格式,格式中定义要保存的具体日志内容。

1、自定义默认格式日志:
log_format nginx_format1 '$remote_addr - $remote_user [$time_local] "$request" ' 
		'$status $body_bytes_sent "$http_referer" ' 	
		'"$http_user_agent" "$http_x_forwarded_for"' 
		'$server_name:$server_port'; 
access_log logs/access.log nginx_format1; 
	
#重启nginx并访问测试日志格式 
==> /apps/nginx/logs/access.log <== 
192.168.0.1 - - [22/Feb/2019:08:44:14 +0800] "GET /favicon.ico HTTP/1.1" 404 162 "-" "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:65.0) Gecko/2 0100101 Firefox/65.0" "-"www.a.net:80
2、自定义json格式日志:

Nginx 的默认访问日志记录内容相对比较单一,默认的格式也不方便后期做日志统计分析,生产环境中通常将nginx日志转换为json日志,然后配合使用ELK做日志收集-统计-分析。

log_format access_json '{"@timestamp":"$time_iso8601",' 
'"host":"$server_addr",' 
'"clientip":"$remote_addr",' 
'"size":$body_bytes_sent,' 
'"responsetime":$request_time,' 
'"upstreamtime":"$upstream_response_time",' 
'"upstreamhost":"$upstream_addr",' 
'"http_host":"$host",' '"uri":"$uri",' 
'"domain":"$host",' 
'"xff":"$http_x_forwarded_for",' 
'"referer":"$http_referer",' 
'"tcp_xff":"$proxy_protocol_addr",' 
'"http_user_agent":"$http_user_agent",' 
'"status":"$status"}'; 
access_log /apps/nginx/logs/access_json.log access_json; 

#重启Nginx并访问测试日志格式 
{"@timestamp":"2019-02- 22T08:55:32+08:00","host":"192.168.7.102","clientip":"192.168.0.1","size":162,"respo nsetime":0.000,"upstreamtime":"-","upstreamhost":"- ","http_host":"www.a.net","uri":"/favicon.ico","domain":"www.a.net","xff": "-","referer":"-","tcp_xff":"","http_user_agent":"Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:65.0) Gecko/20100101 Firefox/65.0","status":"404"}
3、json格式的日志访问统计:
[root@s2 ~]# vim nginx_json.py
#!/usr/bin/env bash 
#coding:utf-8 
#Author:Zhang ShiJie 
status_200= [] 
status_404= []
with open("access_json.log") as f: 
	for line in f.readlines(): 
		line = eval(line) 
		if line.get("status") == "200": 
			status_200.append(line.get) 
		elif line.get("status") == "404": 
			status_404.append(line.get) 
		else:
			print("状态码 ERROR") 
f.close() 
print "状态码200的有--:",len(status_200) 
print "状态码404的有--:",len(status_404) 

#保存日志文件到指定路径并进测试: 
[root@s2 ~]# bash nginx_json.py 
状态码200的有--: 1910 
状态码404的有--: 13
九、压缩功能(基于模块ngx_http_gzip_module)

官方文档: https://nginx.org/en/docs/http/ngx_http_gzip_module.html

[root@s2 pc]# cp /apps/nginx/logs/access.log /data/nginx/html/pc/test.html #大文件测试压缩情况
[root@s2 pc]# echo "test1" > /data/nginx/html/pc/test1.html #小于1k的文件测试是否会压缩 
[root@s2 pc]# vim /apps/nginx/conf/nginx.conf 
	gzip on; #启用gzip压缩,默认关闭
	gzip_comp_level 5; #压缩比由低到高从1到9,默认为1
	gzip_min_length 1k; #gzip压缩的最小文件,小于设置值的文件将不会压缩
	gzip_types text/plain application/javascript application/x-javascript text/cssapplication/xml text/javascript application/x-httpd-php image/jpeg image/gif image/png; #指明仅对哪些类型的资源执行压缩操作;默认为gzip_types text/html,不用显示指定,否则出错
	gzip_vary on; #如果启用压缩,是否在响应报文首部插入“Vary: Accept-Encoding”
	
#重启Nginx并访问测试: curl --head --compressed URI
Encoding: gzip #压缩传输
十、https功能(基于模块ngx_http_ssl_module)

官方文档: https://nginx.org/en/docs/http/ngx_http_ssl_ module.html

server {
	listen 80; 
	listen 443 ssl; 
	#当前虚拟主机使用使用的公钥文件,一般是crt文件
	ssl_certificate /apps/nginx/certs/www.a.net.crt; 
	#当前虚拟主机使用的私钥文件,一般是key文件
	ssl_certificate_key /apps/nginx/certs/www.a.net.key; 
	#配置ssl缓存
	ssl_session_cache shared:sslcache:20m; #在各worker之间使用一个共享的缓存,缓存名称sslcache,缓存空间大小20m
	#客户端连接可以复用ssl session cache中缓存的有效时长,默认5m
	ssl_session_timeout 10m;
	location / { 
		root "/data/nginx/html/mobile";
	}
}
#重启Nginx并访问验证
十一、Rewrite功能(基于用ngx_http_rewrite_module 模块)

官方网站:https://nginx.org/en/docs/http/ngx_http_rewrite_module.html#rewrite
rewrite主要是针对用户请求的URL或者是URI做具体处理,可配置在server、location、if中,编译之前要安装PCRE库,rewrite是nginx服务器的重要功能之一。

1、permanent与redirect,以及自动跳转https:

重要区别:永久重定向会缓存缓存域名解析记录(A记录),但是临时重定向不会缓存。
要求:因业务需要,将访问源域名http:a.com的请求永久重定向到https:a.com。

location / { 
	root /data/nginx/html/pc; 
	index index.html; 
	if ($scheme = http ){ #未加条件判断,会导致死循环
	rewrite / https:a.com permanent; 
	#rewrite / https:a.com redirect; } 
#重启Nginx并访问测试:curl -L -k -i https://www.a.com
2、break与last:
[root@s2 conf.d]# vim pc.conf 
location /break { 
	rewrite ^/break/(.*) /test$1 break; #break不会跳转到其他的
	location return 666 "break"; 
}
location /last { 
	rewrite ^/last/(.*) /test$1 last; #last会跳转到其他的location继续匹配新的URI 
	return 888 "last"; 
}
location /test { 
	return 999 "test"; 
}
#重启Nginx并访问测试:curl -L -i +URL
3、判断文件是否存在:

要求:当用户访问到公司网站的时输入了一个错误的URL,可以将用户重定向至官网首页。

location / { 
	root /data/nginx/html/pc; 
	index index.html; 
	if (!-f $request_filename) { 
		#return 404 "linux35"; 
		rewrite (.*) http://www.a.com/index.html; 
}
#重启Nginx并访问测试:
十二、防盗链功能(基于ngx_http_referer_module模块)

官方网站:https://nginx.org/en/docs/http/ngx_http_referer_module.html
#valid_referers

[root@s2 ~]# vim /apps/nginx/conf/conf.d/pc.conf 
location /images { 
	root /data/nginx/html/pc; 
	index index.html; 
	valid_referers none blocked server_names *.example.com example.* www.example.org/galleries/ ~\.google\.; 
	if ($invalid_referer) { 
		return 403; 
	}
}
	#定义防盗链:
location ^~ /images { 
	root /data/nginx; 
	index index.html; 
	valid_referers none blocked server_names *.a.com www.a.* api.online.test/v1/hostlist ~\.google\. ~\.baidu\.; #定义有效的referer 
	if ($invalid_referer) { #假如是使用其他的无效的referer访问: 
		return 403; #返回状态码403 
	} 
} 
#重启Nginx并访问测试,验证是否提前状态码403
十三、反向代理功能(基于ngx_http_proxy_module模块)

官方文档:https://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_pass
反向代理也叫reverse proxy,指的是代理外网用户的请求到内部的指定web服务器,并将数据返回给用户的一种方式,这是用的比较多的一种方式。
环境准备:
192.168.7.102 #Nginx 代理服务器
192.168.7.103 #后端web A,Apache部署
192.168.7.104 #后端web B,Apache部署

1、部署后端Apache服务器:
[root@s3 ~]# yum install httpd -y 
[root@s3 ~]# echo "web1 192.168.7.103" > /var/www/html/index.html 
[root@s3 ~]# systemctl start httpd && systemctl enable httpd 
[root@s4 ~]# yum install httpd -y 
[root@s4 ~]# echo "web2 192.168.7.104" >> /var/www/html/index.html 
[root@s4 ~]# systemctl start httpd && systemctl enable httpd #访问测试 
[root@s4 ~]# curl http://192.168.7.103 web1 192.168.7.103 
[root@s3 ~]# curl http://192.168.7.104 web2 192.168.7.104
2.1、部署反向代理服务器:
location /web { 
	index index.html; 
	#proxy_pass http://192.168.7.103:80; #不带斜线将访问的/web,等于访问后端服务器http://192.168.7.103:80/web/index.html
	proxy_pass http://192.168.7.103:80/; #带斜线,等于访问后端服务器的http://192.168.7.103:80/index.html
}
#后端web服务器必须要有相对于的访问URL
[root@s3 ~]# mkdir /var/www/html/web 
[root@s3 ~]# echo "web1 page for apache" > /var/www/html/web/index.html
#重启Nginx测试访问效果: 
curl -L http://www.a.net/web/index.html
#Apache的访问日志: 
[root@s3 ~]# tail -f /var/log/httpd/access_log
2.2、反向代理——缓存功能
#非缓存场景压测:
[root@s2 pc]# pwd 
/data/nginx/html/pc 
[root@s2 pc]# scp /apps/nginx/logs/access.log 192.168.7.104:/var/www/html/log.html 
[root@s2 pc]# ab -n 2000 -c200 http://www.magedu.net/web/log.html 
	Total transferred: 3059318000 bytes 
	HTML transferred: 3058760000 bytes 
	Requests per second: 155.14 [#/sec] (mean) 
	Time per request: 1289.166 [ms] (mean) 
	Time per request: 6.446 [ms] (mean, across all concurrent requests) 
	Transfer rate: 231747.94 [Kbytes/sec] received
	
#准备缓存配置:
[root@s2 pc]# vim /apps/nginx/conf/nginx.conf 
#配置在nginx.conf http配置段 
	#定义可用于proxy功能的缓存
	proxy_cache_path /data/nginx/proxycache 
	levels=1:1:1 #定义缓存目录结构层次
	keys_zone=proxycache:20m #指内存中缓存的大小,主要用于存放key和metadata(如:使用次数)
	inactive=120s #缓存有效时间
	max_size=1g; #最大磁盘占用空间,磁盘存入文件内容的缓存空间最大值
[root@s2 pc]# vim /apps/nginx/conf/conf.d/pc.conf 
location /web { #要缓存的URL 或者放在server配置项对所有URL都进行缓存 
	proxy_pass http://192.168.7.104:80/; 
	proxy_set_header clientip $remote_addr; #设定发往后端主机的请求报文的请求首部的值
	#调用缓存功能
	proxy_cache proxycache; 
	proxy_cache_key $request_uri; #缓存中用于“键”的内容
	proxy_cache_valid 200 302 301 1h; #定义对特定响应码的响应内容的缓存时长,定义在http{...}中
	proxy_cache_valid any 1m; 
}
[root@s2 pc]# /apps/nginx/sbin/nginx -t 
nginx: the configuration file /apps/nginx/conf/nginx.conf syntax is ok 
nginx: configuration file /apps/nginx/conf/nginx.conf test is successful 
[root@s2 pc]# systemctl start nginx

#访问web并验证缓存目录 
[root@s2 pc]# curl http://www.magedu.net/web/log.html 
[root@s2 pc]# ab -n 2000 -c200 http://www.magedu.net/web/log.html 
Total transferred: 3059318000 bytes 
HTML transferred: 3058760000 bytes 
Requests per second: 1922.78 [#/sec] (mean) Time per 
request: 104.016 [ms] (mean)
Time per request: 0.520 [ms] (mean, across all concurrent requests) 
Transfer rate: 2872259.55 [Kbytes/sec] received 
#验证缓存目录结构及文件大小 
[root@s2 pc]# tree /data/nginx/proxycache/
└── 
f└── 
	0└── 
		6└── 50b643197ae7d66aaaa5e7e1961b060f 
3 directories, 1 file 
[root@s2 pc]# ll -h /data/nginx/proxycache/f/0/6
/50b643197ae7d66aaaa5e7e1961b060f -rw------- 1 nginx nginx 1.5M Mar 7 14:30 
/data/nginx/proxycache/f/0/6/50b643197ae7d66aaaa5e7e1961b060f 

#验证文件内容: 
[root@s2 pc]# head -n100 
/data/nginx/proxycache/f/0/6/50b643197ae7d66aaaa5e7e1961b060f #会在文件首部添加相应码 
HTTP/1.1 200 OK 
Date: Thu, 07 Mar 2019 18:35:37 GMT 
Server: Apache/2.4.6 (CentOS) 
Last-Modified: Thu, 07 Mar 2019 14:14:47 GMT 
ETag: "175624-58381ba95ac05" 
Accept-Ranges: bytes 
Content-Length: 1529380 
Connection: close 
Content-Type: text/html; charset=UTF-8 
192.168.0.1 - - [18/Feb/2019:10:26:33 +0800] "GET / HTTP/1.1" 200 612
2.3、添加头部报文信息:(基于模块ngx_http_headers_module)

官方网站:https://nginx.org/en/docs/ http/ngx_http_headers_module.html

location /web { 
	proxy_pass http://192.168.7.103:80/; 
	proxy_set_header clientip $remote_addr; 
	proxy_cache proxycache; 
	proxy_cache_key $request_uri; 
	proxy_cache_valid 200 302 301 1h; 
	proxy_cache_valid any 1m; 
	add_header X-Via $server_addr; 
	add_header X-Cache $upstream_cache_status; 
	add_header X-Accel $server_name; 
}
#验证头部信息:curl -I +UIR
3、Nginx http 反向代理高级应用:(基于ngx_http_upstream_module模块)

官方文档: https://nginx.org/en/docs/http/ngx_http_upstr eam_module.html

#自定义一组服务器,配置在http内
upstream webserver { 
	#hash $request_uri consistent; #基于用户请求的uri做hash
	#ip_hash; #源地址hash调度方法,基于的客户端的remote_addr(源地址)做hash计算,以实现会话保持
	#least_conn; #最少连接调度算法,优先将客户端请求调度到当前连接最少的后端服务器
	#配置一个后端web服务器,配置在upstream内,至少要有一个server服务器配置。
	server 192.168.7.103:80 weight=1 fail_timeout=5s max_fails=3; #设置权重,默认为1。#给当前server设置最大活动链接数,默认为0表示没有限制。#对后端服务器连续监测失败多少次就标记为不可用。
	server 192.168.7.104:80 weight=1 fail_timeout=5s max_fails=3; 
	server 192.168.7.101:80 weight=1 fail_timeout=5s max_fails=3 backup; #设置为备份服务器,当所有服务器不可用时将重新启用次服务器。
}
server { 
	listen 80; 
	server_name www.magedu.net; 
	location / { 
		index index.html index.php; 
		root /data/nginx/html/pc; 
	} 
	location /web { 
		index index.html; 
		proxy_pass http://webserver/; 
		proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; #添加客户端IP到报文头 部
	}
}
#重启Nginx 并访问测试 
[root@s2 ~]# curl http://www.magedu.net/web web1 
192.168.7.103 
[root@s2 ~]# curl http://www.magedu.net/web web2 
192.168.7.104
#关闭192.168.7.103和192.168.7.104,测试nginx backup服务器可用性:
[root@s4 ~]# while true;do curl http://www.magedu.net/web;sleep 1;done

#客户端IP透传:
#后端web服务器配置 
1、Apache: 
[root@s4 ~]# vim /etc/httpd/conf/httpd.conf 
LogFormat "%{X-Forwarded-For}i %h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User- Agent}i\"" combined 
#重启apache访问web界面并验证apache日志: 
192.168.7.104 192.168.7.102 - - [05/Mar/2019:00:36:03 +0800] "GET / HTTP/1.0" 200 19 "-" "curl/7.29.0" 192.168.0.1 192.168.7.102 - - [05/Mar/2019:00:40:46 +0800] "GET / HTTP/1.0" 200 19 "-" "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.119 Safari/537.36" 
2、Nginx: [root@s1 conf.d]# cat /apps/nginx/conf/nginx.conf 
"$http_x_forwarded_for"' #默认日志格式就有此配置 
重启nginx访问web界面并验证日志格式: 
192.168.7.102 - - [04/Mar/2019:16:33:24 +0800] "GET // HTTP/1.0" 200 24 "-" "curl/7.29.0" "192.168.7.104" 
192.168.7.102 - - [04/Mar/2019:16:40:51 +0800] "GET / HTTP/1.0" 200 24 "-" "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.119 Safari/537.36" "192.168.0.1"
十四、tcp负载均衡(基于ngx_stream_proxy_module模块实现tcp负载,另外基于模块ngx_stream_upstream_module实现后端服务器分组转发、权重分配、状态监测、调度算法等高级功能。)

官方文档:https://nginx.org/en/docs/stream/ngx_stream_core_module.html

1、负载均衡实例–Redis:
#服务器安装redis
[root@s4 ~]# yum install redis -y 
[root@s4 ~]# vim /etc/redis.conf 
bind 0.0.0.0 
...... 
[root@s4 ~]# systemctl start redis 
[root@s4 ~]# systemctl enable redis 
[root@s4 ~]# ss -tnl | grep 6379 
LISTEN 0 128 *:6379 *:*
#nginx配置:
[root@s2 ~]# mkdir /apps/nginx/conf/tcp 
[root@s2 ~]# cat /apps/nginx/conf/tcp/tcp.conf 
#定义stream
stream { 
	#定义后端服务器
	upstream redis_server { 
		#hash $remote_addr consistent; #定义调度算法
		server 192.168.7.104:6379 max_fails=3 fail_timeout=30s; #定义具体server
	}
	server { 
		listen 192.168.7.102:6379; 
		proxy_connect_timeout 3s; #连接超时时间
		proxy_timeout 3s;  #转发超时时间  
		proxy_pass redis_server; #转发到具体服务
	} 
}
[root@s2 ~]# vim /apps/nginx/conf/nginx.conf 
21 include /apps/nginx/conf/tcp/tcp.conf; #注意此处的include与http模块平级 
#重启nginx并访问测试 
[root@s2 ~]# systemctl restart nginx 
[root@s2 ~]# ss -tnl | grep 6379 
LISTEN 0 128 192.168.7.102:6379 *:* 
#测试通过nginx 负载连接redis: 
[root@s4 ~]# redis-cli -h 192.168.7.102 
192.168.7.102:6379> set name jack 
OK
192.168.7.102:6379> get name 
"jack" 
192.168.7.102:6379>
2、负载均衡实例:MySQL
#服务器安装MySQL:
[root@s4 ~]# yum install mariadb mariadb-server -y 
[root@s4 ~]# systemctl start mariadb 
[root@s4 ~]# mysql_secure_installation #安全初始化 
[root@s4 ~]# systemctl enable mariadb 
[root@s4 ~]# mysql -uroot -p123456 
MariaDB [(none)]> GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY '123456' 
WITH GRANT OPTION; 
MariaDB [(none)]> FLUSH PRIVILEGES; 
Query OK, 0 rows affected (0.00 sec) 
MariaDB [(none)]> exit

#nginx配置:
[root@s2 ~]# cat /apps/nginx/conf/tcp/tcp.conf 
stream { 
	upstream redis_server { 
		server 192.168.7.104:6379 max_fails=3 fail_timeout=30s; 
	}
	upstream mysql_server { 
		least_conn; 
		server 192.168.7.104:3306 max_fails=3 fail_timeout=30s; 
	} 
################################################################### 
	server { 
		listen 192.168.7.102:3306; 
		proxy_connect_timeout 6s; 
		proxy_timeout 15s; 
		proxy_pass mysql_server; 
	} 
	server { 
		listen 192.168.7.102:6379; 
		proxy_connect_timeout 3s; 
		proxy_timeout 3s; 
		proxy_pass redis_server; 
	} 
}
#重启nginx并访问测试: 
[root@s2 ~]# systemctl restart nginx 
#测试通过nginx负载连接MySQL: 
[root@s4 ~]# mysql -uroot -p123456 -h 192.168.7.102 
Welcome to the MariaDB monitor. Commands end with ; or \g. 
Your MariaDB connection id is 32 
Server version: 5.5.60-MariaDB MariaDB Server 
Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others. 
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
MariaDB [(none)]> create database linux34; 
Query OK, 1 row affected (0.00 sec) 
MariaDB [(none)]> show databases; 
+--------------------+
| Database			 | 
+--------------------+ 
| information_schema | 
| linux34			 | 
| mysql				 | 
| performance_schema | 
+--------------------+ 
4 rows in set (0.01 sec) 
MariaDB [(none)]>
十五、实现FastCGI:(基于ngx_http_fastcgi_module模块)

通过fastcgi协议将指定的客户端请求转发至php-fpm处理

十六、LNMP项目实战-WordPress站点搭建:

未完待续,敬请期待……

十七、其他
配置nginx反向代理,实现api.x.com域名代理本地9001端口

参见:nginx反向代理配置详解

你可能感兴趣的:(nginx)