nginx实战配置

nginx实战配置

解决跨域问题

1
2
3
4
5
6
7
8
9
10
11
12
13
14
server {
location / {
root html;
index index.html index.htm;
//允许cros跨域访问
add_header 'Access-Control-Allow-Origin' '*';
}
//自定义本地路径
location /apis {
rewrite ^.+apis/?(.*)$ /$1 break;
include uwsgi_params;
proxy_pass http://www.binghe.com;
}
}

负载均衡

1.负载均衡配置

1
2
3
4
5
6
7
8
9
10
11
12
13
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;
}

限流配置

1.配置参数

limit_req_zone指令设置参数

1
limit_req_zone $binary_remote_addr zone=mylimit:10m rate=10r/s;
  • limit_req_zone定义在http块中,$binary_remote_addr表示保存客户端IP地址的二进制形式。
  • Zone定义IP状态及URL访问频率的共享内存区域。zone=keyword标识区域的名字,以及冒号后面跟区域大小。16000个IP地址的状态信息约1MB,所以示例中区域可以存储160000个IP地址。
  • 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;
0 "";
}

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

缓存配置

1.浏览器缓存

静态资源缓存用expire

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

Response Header中添加了Expires和Cache-Control,

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

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

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

  • HTML文件
  • 经常替换的图片
  • 经常修改的js、css文件
  • 基本不变的API接口

不需要缓存

  • 用户隐私等敏感数据
  • 经常改变的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测试/个性化需求时应禁用掉浏览器缓存。

黑名单

Lua+Redis动态黑名单(OpenResty)

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

1
2
3
4
5
6
7
8
9
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
-------------本文结束-------------
0%