当前位置:  首页>> 技术小册>> Nginx典型应用场景

Nginx安装

注意:这里以CentOS 6.8服务器为例,以root用户身份来安装Nginx。

1.安装依赖环境

  1. yum -y install wget gcc-c++ ncurses ncurses-devel cmake make perl bison openssl openssl-devel gcc* libxml2 libxml2-devel curl-devel libjpeg* libpng* freetype* autoconf automake zlib* fiex* libxml* libmcrypt* libtool-ltdl-devel* libaio libaio-devel bzr libtool

2.安装openssl

  1. wget https://www.openssl.org/source/openssl-1.0.2s.tar.gz
  2. tar -zxvf openssl-1.0.2s.tar.gz
  3. cd /usr/local/src/openssl-1.0.2s
  4. ./config --prefix=/usr/local/openssl-1.0.2s
  5. make
  6. make install

3.安装pcre

  1. wget https://ftp.pcre.org/pub/pcre/pcre-8.43.tar.gz
  2. tar -zxvf pcre-8.43.tar.gz
  3. cd /usr/local/src/pcre-8.43
  4. ./configure --prefix=/usr/local/pcre-8.43
  5. make
  6. make install

4.安装zlib

  1. wget https://sourceforge.net/projects/libpng/files/zlib/1.2.11/zlib-1.2.11.tar.gz
  2. tar -zxvf zlib-1.2.11.tar.gz
  3. cd /usr/local/src/zlib-1.2.11
  4. ./configure --prefix=/usr/local/zlib-1.2.11
  5. make
  6. make

5.安装Nginx

  1. wget http://nginx.org/download/nginx-1.17.2.tar.gz
  2. tar -zxvf nginx-1.17.2.tar.gz
  3. cd /usr/local/src/nginx-1.17.2
  4. ./configure --prefix=/usr/local/nginx-1.17.2 --with-openssl=/usr/local/src/openssl-1.0.2s --with-pcre=/usr/local/src/pcre-8.43 --with-zlib=/usr/local/src/zlib-1.2.11 --with-http_ssl_module
  5. make
  6. make install

这里需要注意的是:安装Nginx时,指定的是openssl、pcre和zlib的源码解压目录,安装完成后Nginx配置文件的完整路径为:/usr/local/nginx-1.17.2/conf/nginx.conf。

Nginx负载均衡配置

1.负载均衡配置

  1. http {
  2. ……
  3. upstream real_server {
  4. server 192.168.103.100:2001 weight=1; #轮询服务器和访问权重
  5. server 192.168.103.100:2002 weight=2;
  6. }
  7. server {
  8. listen 80;
  9. location / {
  10. proxy_pass http://real_server;
  11. }
  12. }
  13. }

2.失败重试配置

  1. upstream real_server {
  2. server 192.168.103.100:2001 weight=1 max_fails=2 fail_timeout=60s;
  3. server 192.168.103.100:2002 weight=2 max_fails=2 fail_timeout=60s;
  4. }

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

三、Nginx限流配置

1.配置参数
limit_req_zone指令设置参数

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. location / {
  2. limit_req zone=mylimit burst=20 nodelay;
  3. proxy_pass http://real_server;
  4. }

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

3.不限流白名单

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

上述配置中,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. location ~* .(jpg|jpeg|png|gif|ico|css|js)$ {
  2. expires 2d;
  3. }

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

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

普通不变的图像,如logo,图标等
js、css静态文件
可下载的内容,媒体文件
协商缓存(add_header ETag/Last-Modified value)

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

用户隐私等敏感数据
经常改变的api数据接口
2.代理层缓存
//缓存路径,inactive表示缓存的时间,到期之后将会把缓存清理

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

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

AB测试/个性化需求时应禁用掉浏览器缓存。

Nginx黑名单

  1. 1.一般配置
  2. location / {
  3. deny 192.168.1.1;
  4. deny 192.168.1.0/24;
  5. allow 10.1.1.0/16;
  6. allow 2001:0db8::/32;
  7. deny all;
  8. }
  1. Lua+Redis动态黑名单(OpenResty)
    安装运行
    1. yum install yum-utils
    2. yum-config-manager --add-repo https://openresty.org/package/centos/openresty.repo
    3. yum install openresty
    4. yum install openresty-resty
    查看
    1. yum --disablerepo="*" --enablerepo="openresty" list available
    运行
    1. service openresty start
    配置(/usr/local/openresty/nginx/conf/nginx.conf)
  1. lua_shared_dict ip_blacklist 1m;
  2. server {
  3. listen 80;
  4. location / {
  5. access_by_lua_file lua/ip_blacklist.lua;
  6. proxy_pass http://real_server;
  7. }
  8. }

lua脚本(ip_blacklist.lua)

  1. local redis_host = "192.168.1.132"
  2. local redis_port = 6379
  3. local redis_pwd = 123456
  4. local redis_db = 2
  5. -- connection timeout for redis in ms.
  6. local redis_connection_timeout = 100
  7. -- a set key for blacklist entries
  8. local redis_key = "ip_blacklist"
  9. -- cache lookups for this many seconds
  10. local cache_ttl = 60
  11. -- end configuration
  12. local ip = ngx.var.remote_addr
  13. local ip_blacklist = ngx.shared.ip_blacklist
  14. local last_update_time = ip_blacklist:get("last_update_time");
  15. -- update ip_blacklist from Redis every cache_ttl seconds:
  16. if last_update_time == nil or last_update_time < ( ngx.now() - cache_ttl ) then
  17. local redis = require "resty.redis";
  18. local red = redis:new();
  19. red:set_timeout(redis_connect_timeout);
  20. local ok, err = red:connect(redis_host, redis_port);
  21. if not ok then
  22. ngx.log(ngx.ERR, "Redis connection error while connect: " .. err);
  23. else
  24. local ok, err = red:auth(redis_pwd)
  25. if not ok then
  26. ngx.log(ngx.ERR, "Redis password error while auth: " .. err);
  27. else
  28. local new_ip_blacklist, err = red:smembers(redis_key);
  29. if err then
  30. ngx.log(ngx.ERR, "Redis read error while retrieving ip_blacklist: " .. err);
  31. else
  32. ngx.log(ngx.ERR, "Get data success:" .. new_ip_blacklist)
  33. -- replace the locally stored ip_blacklist with the updated values:
  34. ip_blacklist:flush_all();
  35. for index, banned_ip in ipairs(new_ip_blacklist) do
  36. ip_blacklist:set(banned_ip, true);
  37. end
  38. -- update time
  39. ip_blacklist:set("last_update_time", ngx.now());
  40. end
  41. end
  42. end
  43. end
  44. if ip_blacklist:get(ip) then
  45. ngx.log(ngx.ERR, "Banned IP detected and refused access: " .. ip);
  46. return ngx.exit(ngx.HTTP_FORBIDDEN);
  47. end

Nginx灰度发布

1.根据Cookie实现灰度发布
根据Cookie查询version值,如果该version值为v1转发到host1,为v2转发到host2,都不匹配的情况下转发到默认配置。

  1. upstream host1 {
  2. server 192.168.2.46:2001 weight=1; #轮询服务器和访问权重
  3. server 192.168.2.46:2002 weight=2;
  4. }
  5. upstream host2 {
  6. server 192.168.1.155:1111 max_fails=1 fail_timeout=60;
  7. }
  8. upstream default {
  9. server 192.168.1.153:1111 max_fails=1 fail_timeout=60;
  10. }
  11. map $COOKIE_version $group {
  12. ~*v1$ host1;
  13. ~*v2$ host2;
  14. default default;
  15. }
  16. lua_shared_dict ip_blacklist 1m;
  17. server {
  18. listen 80;
  19. #set $group "default";
  20. #if ($http_cookie ~* "version=v1"){
  21. # set $group host1;
  22. #}
  23. #if ($http_cookie ~* "version=v2"){
  24. # set $group host2;
  25. #}
  26. location / {
  27. access_by_lua_file lua/ip_blacklist.lua;
  28. proxy_pass http://$group;
  29. }
  30. }

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

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

该分类下的相关小册推荐: