当前位置:   article > 正文

nginx的使用配置_nginx 连接复用

nginx 连接复用

一、初级篇

1、反向代理

proxy_pass 192.168.229.129;
  • 1

2、负载均衡

upstream myserver{
#默认为轮询

#权重
	#server 192.168.229.129 weigh=2;
	#server 192.168.229.130 weigh=4;
	
#分配给最小连接
#least_conn;
	#server 192.168.229.129;
	#server 192.168.229.130;
#ip哈希
#ip_hash;
	#server 192.168.229.129;
	#server 192.168.229.130;
}
http{
	server{
		listen 80
			location / {
				proxy_pass myserver;
}
}
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24

3、动静分离

location ~*/(css|js|img){
# ~*为不区分大小写的正则
	root html;
	index index.html index.htm;
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

3.1 伪静态配置(Url重写)

location /{
	rewrite ^/([0-9]+).html$ /index.jsp?pageNum=$1 break;
	#flag标志位分为 break、last、redirect、permanent
	#break(规则匹配就终止,不会再匹配后面的任何规则)、
	#last(继续往下匹配,匹配到最新的返回)、
	#redirect(返回302临时重定向,地址栏显示重定向后的url)
	#permanent(返回301永久重定向,地址栏显示重定向后的url)
	
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

4、防盗链

location ~*/(css|js|img){
	valid_referers none www.test.com #检测来源,none为检测referer不存在的情况
	if($invalid_referer){
		return 403;
}
# ~*为不区分大小写的正则
	root html;
	index index.html index.htm;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

4.1、配置错误页面

error_page 403 /403.html;
location = /403.html{
	root html;
}
  • 1
  • 2
  • 3
  • 4

5、nginx高可用(keepalived)

#安装
yum install -y keepalived
#配置文件在/etc/keepalived/	
  • 1
  • 2
  • 3

二、高级篇

1、nginx扩实现会话管理

#ip_hash;

#hash $cookie_jessionid;

#hash $request_uri;

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

2、水平拓展集群化

tar -xzvf nginx-goodies-nginx-sticky-module-ng-c78b7dd79d0d.tar.gz

yum install -y openssl-devel

#重新编译安装
./configure -prefix=/usr/local/nginx/ --add-module=/root/nginx/nginx-goodies-nginx-sticky-module-ng-c78b7dd79d0d

make
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

如果报错就修改源码ngx_http_sticky_misc.h

//添加这两行头文件
#include <openssl/sha.h>
#include <openssl/md5.h>
  • 1
  • 2
  • 3
upsteam myserver{
#默认为cookie中key为route来保持会话
	sticky name=route expires=6h;
	server 192.168.229.129:81;
	server 192.168.229.129:82;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

3、keepalive(TCP连接复用)

http {
	keepalive_timeout 65; #保持连接,超过时间没有活动,会让keepalive失效
	keepaline_time 1h; #一个tcp连接总时长,超过之后,强制失效
	send_timeout 60;#默认60s  请求发送等待的相应时间
	keeyalive_requests 1000; #一次tcp,可以并发接收多少个请求
	
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

4、对上游服务器的配置

upsteam myserver{
	keepalive 100;  #连接池的数量
	keepalive_request 1000; #连接复用1000次才close
	keepalive_timeout 65;
}

location / {
	proxy_http_version 1.1;
	proxy_set_header Connection ""; #清除keepalive close,对上游服务器也是用keepalive
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

5、压测对比开启keepalive和没开的效果

  • 不开启keepalive
yum install httpd-tools #安装AB

ab -n 10000 -c 30 http://192.168.229.129:82/ #-n为请求次数,-c为每秒并发
  • 1
  • 2
  • 3

在这里插入图片描述

qps为每秒6800

  • 开启keepalive

在这里插入图片描述

qps为每秒7600

6、内存与缓冲区(在http下或server或location下配置)

proxy_buffering on; #是否缓冲读到的数据
proxy_buffer 32 64k; #缓冲区大小为32个64K大小的内存缓冲块
proxy_max_temp_file  #proxypass读到向磁盘写入的最大值
proxy_temp_file_write_size 8k #每次向磁盘缓冲区写入的大小
##缓冲区的设置在于响应体的大小大于缓冲区的大小并且上游速度慢,下游速度快


client_body_buffer_size #客户端body缓冲区大小
client_body_temp_path
client_max_body_size #最大的请求体大小
client_body_timeout
client_header_timeout
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

7、nginx代理后需要获取用户真实ip

x-forwarded-for 服务端读取该请求头

#nginx配置
location /{
	proxy_set_header X-Forwarded-For $romote_addr;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

8、gzip的使用

##动态压缩 (会导师sendfile不能使用)
location /{
	gzip on;#打开gzip功能
	gzip_buffer 16 8k;
	gzpi_comp_level 6;#gzip压缩等级 1-9   越大压缩速率越慢,传输的数据包越小
	gzip_http_version 1.1;
	gzip_min_length 256;#大于这个值才压缩
	gzip_proxied any;#限制  该为无条件压缩
	gzip_types text/plain application/x-javascript text/css application/xml
	gzip_disable "MSIE[1-6]\.(?.*SV1)";  #针对什么浏览器关掉gzip功能,尽量不配s
	
----------------------------------------------------
##静态压缩,该为一个模块,需要编译,它会将nginx上的静态文件压缩,需要时解压传输个客户端,主要用于节省空间
./configure --prefix=/usr/local/nginx/ --with-http_gzip_static_module

make
##配置静态压缩,
gzip_static always;
gunzip on;

}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

9、rsync同步源文件

#两端都安装
#nginx1
yum install -y rsync
#nginx2拉取nginx1变动的静态文件

#配置/etc/rsyncd.conf
 [ftp]
        path = /home/ftp  #需要监控的目录

#启动
rsync --daemon

#nginx2

yum install -y rsync

rsync --list-only 192.168.229.129::ftp/  #查看nginx1的文件
rsync -avz 192.168.229.129::ftp/ /opt/nginx2/html #同步 

        

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

10、缓存

10.1 协商缓存

  • 响应头的etag和Last Modified属于协商缓存
  • etag属于hash,请求获得资源后会计算etag,当再次请求会比对etag,相同nginx返回304获取浏览器缓存。

10.2 关闭协商缓存(实时请求数据)

location / {
	etag off;
	#add_header Last-Modified **;  #设置上一次更新时间为空
	#if_modified_since off; #强制关闭缓存,二者选一个都行
}
  • 1
  • 2
  • 3
  • 4
  • 5

10.3 强制缓存

location /{
	etag off;
	#add_header Last-Modified **;  #设置上一次更新时间为空
	if_modified_since off; #强制关闭协商缓存,二者选一个都行
	expires 300s;
	add_header cache-contorl "max-age:300"; 
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

10.4 CDN缓存

10.5 正向代理

server{
	resolver 8.8.8.8 #google提供的免费的dns服务器
}
location / {
	proxy_pass $scheme://$host$request_uri;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

10.6 反向代理缓存(proxy_cache)

http{
	proxy_cache_path /ngx_tmp_levels=1:2 keys_zone=test_cache:100m inactive= 1d max_size=10g;   #临时文件存放在磁盘,存放1d,索引占用内存100m大小
	server  xxx{
	location /{
		add_header Nginx-Cache "$upstream_cache_status";
		proxy_cache test_cache  #与key_zone对应
		proxy_cache_valid 1h; #配置过期时间	
}
}
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

11.7 断点续传

对于一些视频播放,用于点击到视频的某个位置,浏览器会发起range请求,请求到对应位置在加载。

location /{
	proxy_set_header Range $http_range;
}
  • 1
  • 2
  • 3

12. error page、return、location



server{
	error_page 404 =302 http://baidu.com;
	error_page 401 =200 /401.html;

	error_page 404 = @666;

	location @666{
		add_header content-type "text/html";
		return 200 "内容";
}
	error_page 500 502 503 503 /50x.html;
	location = /50x.html{
			root html;
}
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

13、QPS限制

  • 13.1 漏桶算法
http{
	limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;  #以二进制的形式记录ip到10m的缓冲区,如果不用$binary,就会以字符串的形式记录,qps=1


server{
	location /{
		limit req zone=one burst=5 nodelay;   #漏桶,nodelay为队列后面进不来的快速失败,不再等待
}
}
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 13.2 令牌桶算法

每秒生成N个令牌,每进来一个请求可以拿走n个或一个令牌,享受不同的带宽。

limit_rate_after 1M  #传输1M后限速
limit_rate 1k;  #每秒提供一个1K的令牌
  • 1
  • 2
  • 13.3 限制并发数(计数器算法)
http{
	limit_conn_zone $binary_romote_addr zone=two 10m;

server{
	location /{
		limit_conn two 1; #可以配合limit_req和limit_rate使用
}
}
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

14、日志

http {
	access_log /ngx_log/nginx-access.log buffer=32k #配置日志缓冲区
}
  • 1
  • 2
  • 3

15、Lua二次开发

  • 15.1 安装openresty
docker pull openresty/openresty
docker run --name openresty -p 80:80 -d openresty/openresty
mkdir /opt/openresty
cd /opt/openresty
# 存放nginx的配置文件
mkdir conf
# 存放lua脚本
mkdir lua

docker cp openresty:/usr/local/openresty/nginx/conf/nginx.conf /opt/openresty/conf
# 拷贝lua库
docker cp openresty:/usr/local/openresty/lualib /opt/openresty/
docker rm -f openresty

docker run --name openresty \
-v /opt/openresty/conf/nginx.conf:/usr/local/openresty/nginx/conf/nginx.conf \
-v /opt/openresty/lua/:/usr/local/openresty/nginx/lua \
-v /opt/openresty/lualib/:/usr/local/openresty/lualib \
-p 80:80 -d openresty/openresty


  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 15.2 Idea下载EmmyLua插件
  • 15.3 下载lua.exe
  • 15.4 编写测试lua
lua_code_cache off; #开启热部署,不用重启nginx
lua_shared_dict_shared_data 1m; #内存缓存   可以通过lua使用ngx.shared.shared_data获取缓存使用get和set设值,这个是保证了原子性。
server{
	listen 80;
	server_name 192.168.229.129;
	
	location /lua{
		default_type text/html;

		content_by_lua_file lua/test.lua;
} 
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

test.lua

ngx.say("hello World")
  • 1
  • 15.5 连接redis
 local redis = require "resty.redis"  --引入redis
                local red = redis:new()  --``创建连接

                red:set_timeouts(1000, 1000, 1000) -- 1 sec

  local ok, err = red:connect("192.168.229.129", 6379)
 if not ok then
                    ngx.say("failed to connect: ", err)
                    return
                end

                ok, err = red:set("dog", "an animal")
                if not ok then
                    ngx.say("failed to set dog: ", err)
                    return
                end

                ngx.say("set result: ", ok)

                local res, err = red:get("dog")
                if not res then
                    ngx.say("failed to get dog: ", err)
                    return
                end

                if res == ngx.null then
                    ngx.say("dog not found.")
                    return
                end


              ngx.say("dog: ", res)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 15.6 连接 mysql
 local mysql = require "resty.mysql"
                 local db, err = mysql:new()
                 if not db then
                     ngx.say("failed to instantiate mysql: ", err)
                     return
                 end
 
                 db:set_timeout(1000) -- 1 sec
 
 
                 local ok, err, errcode, sqlstate = db:connect{
                     host = "192.168.229.129",
                     port = 3306,
                     database = "test",
                     user = "root",
                     password = "123456",
                     charset = "utf8",
                     max_packet_size = 1024 * 1024,
                 }
 
 
                 ngx.say("connected to mysql.<br>")
 
 
 
                 local res, err, errcode, sqlstate = db:query("drop table if exists cats")
                 if not res then
                     ngx.say("bad result: ", err, ": ", errcode, ": ", sqlstate, ".")
                     return
                 end
 
 
                 res, err, errcode, sqlstate =
                     db:query("create table cats "
                              .. "(id serial primary key, "
                              .. "name varchar(5))")
                 if not res then
                     ngx.say("bad result: ", err, ": ", errcode, ": ", sqlstate, ".")
                     return
                 end
 
                 ngx.say("table cats created.")
 
 
 
                 res, err, errcode, sqlstate =
                     db:query("select * from t_emp")
                 if not res then
                     ngx.say("bad result: ", err, ": ", errcode, ": ", sqlstate, ".")
                     return
                 end
 
                 local cjson = require "cjson"
                 ngx.say("result: ", cjson.encode(res))
 
 
                 local ok, err = db:set_keepalive(10000, 100)
                 if not ok then
                     ngx.say("failed to set keepalive: ", err)
                     return
                 end
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/羊村懒王/article/detail/733321
推荐阅读
相关标签
  

闽ICP备14008679号