一、Nginx安装(基于CentOS 6.5)

1.yum命令安装

yum install nginx –y
(若不能安装,执行命令yum install epel-release)

2. 启动、停止和重启

service nginx start
service nginx stop
service nginx restart
浏览器中 输入服务器的 ip 地址,即可看到相应信息

3. 其他信息

rpm -ql nginx 来查看安装路径
yum remove nginx 来卸载 
nginx -s reload 配置热更新

、Nginx负载均衡配置(/etc/nginx/nginx.conf)

  1. 负载均衡配置
http {
……
upstream real_server {
server 192.168.103.100:2001 weight=1; #轮询服务器和访问权重
server 192.168.103.100:2002 weight=2;
} server {
listen 80; location / {
proxy_pass http://real_server;
}
}
}

  

   2.失败重试配置
1
2
3
4
upstream real_server {
   server 192.168.103.100:2001 weight=1 max_fails=2 fail_timeout=60s;
   server 192.168.103.100:2002 weight=2 max_fails=2 fail_timeout=60s;
}

意思是在fail_timeout时间内失败了max_fails次请求后,则认为该上游服务器不可用,然后将该服务地址踢除掉。fail_timeout时间后会再次将该服务器加入存活列表,进行重试。

三、Nginx限流配置

  1. 配置参数

limit_req_zone指令设置参数

1
limit_req_zone $binary_remote_addr zone=mylimit:10m rate=10r/s;

1)limit_req_zone定义在http块中,$binary_remote_addr表示保存客户端IP地址的二进制形式。
2)Zone定义IP状态及URL访问频率的共享内存区域。zone=keyword标识区域的名字,以及冒号后面跟区域大小。16000个IP地址的状态信息约1MB,所以示例中区域可以存储160000个IP地址。
3)Rate定义最大请求速率。示例中速率不能超过每秒10个请求。

2.设置限流

1
2
3
4
location / {
        limit_req zone=mylimit burst=20 nodelay;
        proxy_pass http://real_server;
}

burst排队大小,nodelay不限制单个请求间的时间

3.不限流白名单

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
geo $limit {
default              1;
192.168.2.0/24  0;
}
 
map $limit $limit_key {
1 $binary_remote_addr;
"";
}
 
limit_req_zone $limit_key zone=mylimit:10m rate=1r/s;
 
location / {
        limit_req zone=mylimit burst=1 nodelay;
        proxy_pass http://real_server;
}

上述配置中,192.168.2.0/24网段的IP访问是不限流的,其他限流。

IP后面的数字含义:

24表示子网掩码:255.255.255.0

16表示子网掩码:255.255.0.0

8表示子网掩码:255.0.0.0

四、Nginx缓存配置

  1. 浏览器缓存

静态资源缓存用expire

1
2
3
location ~*  .(jpg|jpeg|png|gif|ico|css|js)$ {
   expires 2d;
}

Response Header中添加了Expires和Cache-Control

静态资源包括(一般缓存)

1)普通不变的图像,如logo,图标等
2)js、css静态文件
3)可下载的内容,媒体文件

协商缓存(add_header ETag/Last-Modified value)

1)HTML文件
2)经常替换的图片
3)经常修改的js、css文件
4)基本不变的API接口

不需要缓存

1)用户隐私等敏感数据

2)经常改变的api数据接口

2.代理层缓存

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//缓存路径,inactive表示缓存的时间,到期之后将会把缓存清理
proxy_cache_path /data/cache/nginx/ levels=1:2 keys_zone=cache:512m inactive = 1d max_size=8g;
 
location / {
    location ~ \.(htm|html)?$ {
        proxy_cache cache;
        proxy_cache_key    $uri$is_args$args;     //以此变量值做HASH,作为KEY
        //HTTP响应首部可以看到X-Cache字段,内容可以有HIT,MISS,EXPIRES等等
        add_header X-Cache $upstream_cache_status;
        proxy_cache_valid 200 10m;
        proxy_cache_valid any 1m;
        proxy_pass  http://real_server;
        proxy_redirect     off;
    }
    location ~ .*\.(gif|jpg|jpeg|bmp|png|ico|txt|js|css)$ {
        root /data/webapps/edc;
        expires      3d;
        add_header Static Nginx-Proxy;
    }
}

在本地磁盘创建一个文件目录,根据设置,将请求的资源以K-V形式缓存在此目录当中,KEY需要自己定义(这里用的是url的hash值),同时可以根据需要指定某内容的缓存时长,比如状态码为200缓存10分钟,状态码为301,302的缓存5分钟,其他所有内容缓存1分钟等等。
        可以通过purger的功能清理缓存。
        AB测试/个性化需求时应禁用掉浏览器缓存。

五、Nginx黑名单

1.一般配置

1
2
3
4
5
6
7
location / {
    deny  192.168.1.1;
    deny 192.168.1.0/24;
    allow 10.1.1.0/16;
    allow 2001:0db8::/32;
    deny  all;
}

2. Lua+Redis动态黑名单(OpenResty)

1)安装运行

1
2
3
4
5
6
7
8
yum install yum-utils
yum-config-manager --add-repo https://openresty.org/package/centos/openresty.repo
yum install openresty
yum install openresty-resty
查看
yum --disablerepo="*" --enablerepo="openresty" list available
运行
service openresty start

2) 配置(/usr/local/openresty/nginx/conf/nginx.conf)

1
2
3
4
5
6
7
8
9
10
lua_shared_dict ip_blacklist 1m;
 
server {
    listen  80;
 
    location / {
        access_by_lua_file lua/ip_blacklist.lua;
        proxy_pass http://real_server;
    }
}

lua脚本(ip_blacklist.lua)

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
local redis_host    = "192.168.1.132"
local redis_port    = 6379
local redis_pwd     = 123456
local redis_db = 2
 
-- connection timeout for redis in ms.
local redis_connection_timeout = 100
 
-- a set key for blacklist entries
local redis_key     = "ip_blacklist"
 
-- cache lookups for this many seconds
local cache_ttl     = 60
 
-- end configuration
 
local ip                = ngx.var.remote_addr
local ip_blacklist      = ngx.shared.ip_blacklist
local last_update_time  = ip_blacklist:get("last_update_time");
 
-- update ip_blacklist from Redis every cache_ttl seconds:
if last_update_time == nil or last_update_time < ( ngx.now() - cache_ttl ) then
 
  local redis = require "resty.redis";
  local red = redis:new();
 
  red:set_timeout(redis_connect_timeout);
 
  local ok, err = red:connect(redis_host, redis_port);
  if not ok then
    ngx.log(ngx.ERR, "Redis connection error while connect: " .. err);
  else
    local ok, err = red:auth(redis_pwd)
    if not ok then
      ngx.log(ngx.ERR, "Redis password error while auth: " .. err);
    else
        local new_ip_blacklist, err = red:smembers(redis_key);
        if err then
            ngx.log(ngx.ERR, "Redis read error while retrieving ip_blacklist: " .. err);
        else
        ngx.log(ngx.ERR, "Get data success:" .. new_ip_blacklist)
          -- replace the locally stored ip_blacklist with the updated values:
            ip_blacklist:flush_all();
          for index, banned_ip in ipairs(new_ip_blacklist) do
            ip_blacklist:set(banned_ip, true);
          end
          -- update time
          ip_blacklist:set("last_update_time", ngx.now());
      end
    end
  end
end
 
if ip_blacklist:get(ip) then
  ngx.log(ngx.ERR, "Banned IP detected and refused access: " .. ip);
  return ngx.exit(ngx.HTTP_FORBIDDEN);
end

六、Nginx灰度发布

  1. 根据Cookie实现灰度发布

根据Cookie查询version值,如果该version值为v1转发到host1,为v2转发到host2,都不匹配的情况下转发默认。

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
upstream host1 {
   server 192.168.2.46:2001 weight=1;  #轮询服务器和访问权重
   server 192.168.2.46:2002 weight=2;
}
 
upstream host2 {
   server 192.168.1.155:1111  max_fails=1 fail_timeout=60;
}
 
upstream default {
   server 192.168.1.153:1111  max_fails=1 fail_timeout=60;
}
 
map $COOKIE_version $group {
   ~*v1$ host1;
   ~*v2$ host2;
   default default;
}
 
lua_shared_dict ip_blacklist 1m;
 
server {
    listen  80;
 
    #set $group "default";
    #if ($http_cookie ~* "version=v1"){
    #    set $group host1;
    #}
    #if ($http_cookie ~* "version=v2"){
    #    set $group host2;
    #}
 
    location / {
        access_by_lua_file lua/ip_blacklist.lua;
        proxy_pass http://$group;
    }
}

2. 根据来路IP实现灰度发布

1
2
3
4
5
6
7
8
9
server {
  ……………
  set $group default;
  if ($remote_addr ~ "192.168.119.1") {
      set $group host1;
  }
  if ($remote_addr ~ "192.168.119.2") {
      set $group host2;
  }

3. 更细粒度灰度发布

可用lua脚本实现,参考开源项目:https://github.com/CNSRE/ABTestingGateway

Nginx配置之负载均衡、限流、缓存、黑名单和灰度发布的更多相关文章

  1. nginx配置优化+负载均衡+动静分离详解

    nginx配置如下: #指定nginx进程运行用户以及用户组user www www;#nginx要开启的进程数为8worker_processes 8;#全局错误日志文件#debug输出日志最为详细 ...

  2. [转] nginx配置优化+负载均衡+动静分离(附带参数解析)

    #指定nginx进程运行用户以及用户组user www www;#nginx要开启的进程数为8worker_processes  8;#全局错误日志文件#debug输出日志最为详细,而crit输出日志 ...

  3. nginx 配置https 负载均衡

    1.Winodw安装openssl工具(生成SSL证书用的)免编译版本下载: http://slproweb.com/products/Win32OpenSSL.html 注意:如果openssl在使 ...

  4. nginx配置+uwsgi+负载均衡配置

    nginx静态文件配置 location /static{ alias /var/www/myApp/static; } sudo mkdir -vp /var/www/myApp/static/ s ...

  5. nginx配置实现负载均衡

    一.负载均衡的作用 1.转发功能 按照一定的算法[权重.轮询],将客户端请求转发到不同应用服务器上,减轻单个服务器压力,提高系统并发量. 2.故障移除 通过心跳检测的方式,判断应用服务器当前是否可以正 ...

  6. Nginx配置实例-负载均衡实例:平均访问多台服务器

    场景 Nginx配置实例-反向代理实例:根据访问的路径跳转到不同端口的服务中: https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/10 ...

  7. nginx 配置实例-负载均衡

    1.实现效果 (1)浏览器地址栏输入地址 http://www.123.com/edu/a.html,负载均衡效果,平均 8080 和 8081 端口中 2.准备工作 (1)准备两台 tomcat 服 ...

  8. Nginx配置简单负载均衡

    前提:因为本次需要两个软件在本机不同端口提供http服务,于是我准备一个tomcat在8080端口,另一个nodejs程序在3000端口,前者自不用提,后者可以到https://www.cnblogs ...

  9. Nginx配置及负载均衡

    转载:http://www.cnblogs.com/jingmoxukong/p/5945200.html nginx简易教程   目录 Nginx  概述  安装与使用  nginx 配置实战  参 ...

随机推荐

  1. Apache强制WWW跳转以及强制HTTPS加密跳转的方法

    一般我会较多的使用WORDPRESS程序,其在安装的时候我们如果直接用WWW打开,或者在后台设置WWW域名则默认会强制301指向WWW站点域名.而这里有使用ZBLOG或者TYPECHO等其他博客程序则 ...

  2. inout口在modelsim仿真的方法

    //主要是// 和**********部分是关键 1 `timescale 1ns/1ns module tb(); reg main_clk; :] addr; reg FPGA_CS0;//FPG ...

  3. OpenCV3如何使用SIFT和SURF Where did SIFT and SURF go in OpenCV 3?

    Installation and Usage If you have previous/other version of OpenCV installed (e.g. cv2 module in th ...

  4. ts文件分析(纯c解析代码)

    参考链接: 1. MPEG-2 TS码流分析 https://blog.csdn.net/zhubin215130/article/details/8958567 TS Header PAT PMT ...

  5. CSS3动画与JS动画的优缺点?

    JS动画: 缺点:1.JS在浏览器的主线程中运行,而主线程还有其他的js脚本,样式布局,绘制任务等,对其干扰可能导致线程出现阻塞,从而造成丢帧的情况. 2.JS动画代码复杂度高于CSS3动画. 优点: ...

  6. DevExpress ASP.NET Core Controls 2019发展蓝图(No.2)

    本文主要为大家介绍DevExpress ASP.NET Core Controls 2019年的官方发展蓝图,更多精彩内容欢迎持续收藏关注哦~ [DevExpress ASP.NET Controls ...

  7. Node.js 串口通讯 node-serialport 使用说明

    官网:https://serialport.io/en/ 安装:npm install serialport Parsers说明:parser-byte-length:大概意思是定义了一个长度为len ...

  8. 怎样将virtualbox中的虚拟系统安装到c盘以外的盘

    首先在安装的时候是可以选择虚拟机文件的位置的,如果当时没注意,只能现在移动一下了,很简单 首先将 C:/Users目录下的.VirtualBox和VirtualBox VMs两个文件拷贝到你愿意放的位 ...

  9. unity UI如何开启(显示)或者关闭(隐藏)Panel界面最好?

    https://segmentfault.com/a/1190000012357091 unity UI如何开启(显示)或者关闭(隐藏)Panel界面,相信大家都是知道的,但是如何做最好呢? 可能大家 ...

  10. mybatis(3)---传参数的方法

    1.传一个参数 //接口方法List<EmpVo> find(int empId); //xml配置 <select resultType="com.ht.mapper.E ...