头部背景图片
今晚月色很美、你说是的 -- ZeMing |
今晚月色很美、你说是的 -- ZeMing |

nginx安装 Lua 笔记 + Cache + Image_filter + lua_status (待整理)

#lua笔记记录

#lua经典的模块流转图,一图胜千言
image

#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
init_by_lua            http
set_by_lua server, server if, location, location if
rewrite_by_lua http, server, location, location if
access_by_lua http, server, location, location if
content_by_lua location, location if
header_filter_by_lua http, server, location, location if
body_filter_by_lua http, server, location, location if
log_by_lua http, server, location, location if
{
set_by_lua: 流程分支处理判断变量初始化
rewrite_by_lua: 转发、重定向、缓存等功能(例如特定请求代理到外网)
access_by_lua: IP准入、接口权限等情况集中处理(例如配合iptable完成简单防火墙)
content_by_lua: 内容生成
header_filter_by_lua: 应答HTTP过滤处理(例如添加头部信息)
body_filter_by_lua: 应答BODY过滤处理(例如完成应答内容统一成大写)
log_by_lua: 会话完成后本地异步完成日志记录(日志可以记录在本地,还可以同步到其他机器)
}

1、output API(ngx.say和ngx.send_headers)

2、control API(ngx.exit和ngx.exec)

3、subrequest API(ngx.location.capture和ngx.location.capture_multi)

4、cosocket API(ngx.socket.tcp和ngx.req.socket)

header_filter_by_lua 不支持 1234
body_filter_by_lua 不支持 1234


#nginx_lua_doc
https://github.com/openresty/lua-nginx-module#status
#Nginx_lua_Doc_CN
https://moonbingbing.gitbooks.io/openresty-best-practices/openresty/sub_request.html


image_filter resize 20 20;
image_filter_jpeg_quality 75;
image_filter_buffer 500M;
proxy_set_header Host $http_host;
proxy_pass http://10.129.8.37/;
proxy_ignore_headers "Cache-Control" "Expires" "Set-Cookie" ;

ngx.req.get_headers()["Location"]

一个复杂lua 实例

image

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

location ~* /resize([\d-]+)/(.*) {
content_by_lua '
local request_uri = ngx.var.request_uri
local host = ngx.var.host
local var = string.format("%s%s", host, request_uri)
local args1 = ngx.var.args
local var1 = ""
local var2 = ""
local size = ""
if args1 == nil then
args1 = ""
size = ngx.var[1]
var1 = string.format("%s/%s", host, ngx.var[2])
var3 = string.format("/%s/%s", size, ngx.var[2])

else
size = ngx.var[1]
var1 = string.format("%s/%s?%s", host, ngx.var[2],args1)
var3 = string.format("/%s/%s?%s", size, ngx.var[2],args1)
end
local res = ngx.location.capture("/proxyto/" .. var1, { method = ngx.HTTP_HEAD})
if res.status == 200 then
ngx.exec(var3)
elseif res.status == 404 then
ngx.say(res.status)
ngx.say("test404 " , var1)
elseif res.status == 302 then
local location = res.header["Location"]
local m, err = ngx.re.match(location, "//([^/]+)(/.*)")
if not m then
ngx.exit(555)
end
host = m[1]
uri = m[2]
var2 = string.format("//%s/%s%s", host, size , uri)
ngx.redirect(var2)
else
ngx.exit(res.status)
end

';
}
#proxy to
location ~ /proxyto/(.*) {
proxy_pass http://$1$is_args$query_string;
}


#Aliyun lua介绍
https://zhuanlan.zhihu.com/p/28382165
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
 方法和常量 
######################


ngx.arg[index] #ngx指令参数,当这个变量在set_by_lua或者set_by_lua_file内使用的时候是只读的,指的是在配置指令输入的参数.
ngx.var.varname #读写NGINX变量的值,最好在lua脚本里缓存变量值,避免在当前请求的生命周期内内存的泄漏
ngx.config.ngx_lua_version #当前ngx_lua模块版本号
ngx.config.nginx_version #nginx版本
ngx.worker.exiting #当前worker进程是否正在关闭
ngx.worker.pid #当前worker进程的PID
ngx.config.nginx_configure #编译时的./configure命令选项
ngx.config.prefix #编译时的prefix选项

core constans: #ngx_lua 核心常量
ngx.OK (0)
ngx.ERROR (-1)
ngx.AGAIN (-2)
ngx.DONE (-4)
ngx.DECLINED (-5)
ngx.nil
http method constans: #经常在ngx.location.catpure和ngx.location.capture_multi方法中被调用.
ngx.HTTP_GET
ngx.HTTP_HEAD
ngx.HTTP_PUT
ngx.HTTP_POST
ngx.HTTP_DELETE
ngx.HTTP_OPTIONS
ngx.HTTP_MKCOL
ngx.HTTP_COPY
ngx.HTTP_MOVE
ngx.HTTP_PROPFIND
ngx.HTTP_PROPPATCH
ngx.HTTP_LOCK
ngx.HTTP_UNLOCK
ngx.HTTP_PATCH
ngx.HTTP_TRACE
http status constans: #http请求状态常量
ngx.HTTP_OK (200)
ngx.HTTP_CREATED (201)
ngx.HTTP_SPECIAL_RESPONSE (300)
ngx.HTTP_MOVED_PERMANENTLY (301)
ngx.HTTP_MOVED_TEMPORARILY (302)
ngx.HTTP_SEE_OTHER (303)
ngx.HTTP_NOT_MODIFIED (304)
ngx.HTTP_BAD_REQUEST (400)
ngx.HTTP_UNAUTHORIZED (401)
ngx.HTTP_FORBIDDEN (403)
ngx.HTTP_NOT_FOUND (404)
ngx.HTTP_NOT_ALLOWED (405)
ngx.HTTP_GONE (410)
ngx.HTTP_INTERNAL_SERVER_ERROR (500)
ngx.HTTP_METHOD_NOT_IMPLEMENTED (501)
ngx.HTTP_SERVICE_UNAVAILABLE (503)
ngx.HTTP_GATEWAY_TIMEOUT (504)

Nginx log level constants: #错误日志级别常量 ,这些参数经常在ngx.log方法中被使用.
ngx.STDERR
ngx.EMERG
ngx.ALERT
ngx.CRIT
ngx.ERR
ngx.WARN
ngx.NOTICE
ngx.INFO
ngx.DEBUG

##################
#API中的方法:
##################
print() #与 ngx.print()方法有区别,print() 相当于ngx.log()
ngx.ctx #这是一个lua的table,用于保存ngx上下文的变量,在整个请求的生命周期内都有效,详细参考官方
ngx.location.capture() #发出一个子请求,详细用法参考官方文档。
ngx.location.capture_multi() #发出多个子请求,详细用法参考官方文档。
ngx.status #读或者写当前请求的相应状态. 必须在输出相应头之前被调用.
ngx.header.HEADER #访问或设置http header头信息,详细参考官方文档。
ngx.req.set_uri() #设置当前请求的URI,详细参考官方文档
ngx.set_uri_args(args) #根据args参数重新定义当前请求的URI参数.
ngx.req.get_uri_args() #返回一个LUA TABLE,包含当前请求的全部的URL参数
ngx.req.get_post_args() #返回一个LUA TABLE,包括所有当前请求的POST参数
ngx.req.get_headers() #返回一个包含当前请求头信息的lua table.
ngx.req.set_header() #设置当前请求头header某字段值.当前请求的子请求不会受到影响.
ngx.req.read_body() #在不阻塞ngnix其他事件的情况下同步读取客户端的body信息.[详细]
ngx.req.discard_body() #明确丢弃客户端请求的body
ngx.req.get_body_data() #以字符串的形式获得客户端的请求body内容
ngx.req.get_body_file() #当发送文件请求的时候,获得文件的名字
ngx.req.set_body_data() #设置客户端请求的BODY
ngx.req.set_body_file() #通过filename来指定当前请求的file data。
ngx.req.clear_header() #清求某个请求头
ngx.exec(uri,args) #执行内部跳转,根据uri和请求参数
ngx.redirect(uri, status) #执行301或者302的重定向。
ngx.send_headers() #发送指定的响应头
ngx.headers_sent #判断头部是否发送给客户端ngx.headers_sent=true
ngx.print(str) #发送给客户端的响应页面
ngx.say() #作用类似ngx.print,不过say方法输出后会换行
ngx.log(log.level,...) #写入nginx日志
ngx.flush() #将缓冲区内容输出到页面(刷新响应)
ngx.exit(http-status) #结束请求并输出状态码
ngx.eof() #明确指定关闭结束输出流
ngx.escape_uri() #URI编码(本函数对逗号,不编码,而php的urlencode会编码)
ngx.unescape_uri() #uri解码
ngx.encode_args(table) #将tabel解析成url参数
ngx.decode_args(uri) #将参数字符串编码为一个table
ngx.encode_base64(str) #BASE64编码
ngx.decode_base64(str) #BASE64解码
ngx.crc32_short(str) #字符串的crs32_short哈希
ngx.crc32_long(str) #字符串的crs32_long哈希
ngx.hmac_sha1(str) #字符串的hmac_sha1哈希
ngx.md5(str) #返回16进制MD5
ngx.md5_bin(str) #返回2进制MD5
ngx.today() #返回当前日期yyyy-mm-dd
ngx.time() #返回当前时间戳
ngx.now() #返回当前时间
ngx.update_time() #刷新后返回
ngx.localtime() #返回 yyyy-mm-dd hh:ii:ss
ngx.utctime() #返回yyyy-mm-dd hh:ii:ss格式的utc时间
ngx.cookie_time(sec) #返回用于COOKIE使用的时间
ngx.http_time(sec) #返回可用于http header使用的时间
ngx.parse_http_time(str) #解析HTTP头的时间
ngx.is_subrequest #是否子请求(值为 true or false)
ngx.re.match(subject,regex,options,ctx) #ngx正则表达式匹配,详细参考官网
ngx.re.gmatch(subject,regex,opt) #全局正则匹配
ngx.re.sub(sub,reg,opt) #匹配和替换(未知)
ngx.re.gsub() #未知
ngx.shared.DICT #ngx.shared.DICT是一个table 里面存储了所有的全局内存共享变量
ngx.shared.DICT.get
ngx.shared.DICT.get_stale
ngx.shared.DICT.set
ngx.shared.DICT.safe_set
ngx.shared.DICT.add
ngx.shared.DICT.safe_add
ngx.shared.DICT.replace
ngx.shared.DICT.delete
ngx.shared.DICT.incr
ngx.shared.DICT.flush_all
ngx.shared.DICT.flush_expired
ngx.shared.DICT.get_keys
ndk.set_var.DIRECTIVE #不懂
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
62
63
64
65
66
67
ngx_lua模块API说明
#Ngx指令
lua_code_cache on | off;
作用:打开或关闭 Lua 代码缓存,影响以下指令: set_by_lua_file , content_by_lua_file, rewrite_by_lua_file, access_by_lua_file 及强制加载或者reload Lua 模块等.缓存开启时修改LUA代码需要重启nginx,不开启时则不用。开发阶段一般关闭缓存。
作用域:main, server, location, location if

lua_regex_cache_max_entries 1024;
作用:未知(貌似是限定缓存正则表达式处理结果的最大数量)

lua_package_path .../path... ;
作用:设置用lua代码写的扩展库路径。
例:lua_package_path '/foo/bar/?.lua;/blah/?.lua;;';

lua_package_cpath '/bar/baz/?.so;/blah/blah/?.so;;';
作用:设置C扩展的lua库路径。

set_by_lua $var '<lua-script>' [$arg1 $arg2];
set_by_lua_file $var <path-to-lua-script-file> [$arg1 $arg2 ...];
作用:设置一个Nginx变量,变量值从lua脚本里运算由return返回,可以实现复杂的赋值逻辑;此处是阻塞的,Lua代码要做到非常快.
另外可以将已有的ngx变量当作参数传进Lua脚本里去,由ngx.arg[1],ngx.arg[2]等方式访问。
作用域:main, server, location, server if, location if
处理阶段:rewrite

content_by_lua '<lua script>';
content_by_lua_file luafile;
作用域:location, location if
说明:内容处理器,接收请求处理并输出响应,content_by_lua直接在nginx配置文件里编写较短Lua代码后者使用lua文件。

rewrite_by_lua '<lua script>'
rewrite_by_lua_file lua_file;
作用域:http, server, location, location if
执行内部URL重写或者外部重定向,典型的如伪静态化的URL重写。其默认执行在rewrite处理阶段的最后.
注意,在使用rewrite_by_lua时,开启rewrite_log on;后也看不到相应的rewrite log。

access_by_lua 'lua code';
access_by_lua_file lua_file.lua;
作用:用于访问控制,比如我们只允许内网ip访问,可以使用如下形式。
access_by_lua '
if ngx.req.get_uri_args()["token"] ~= "123" then
return ngx.exit(403)
end ';
作用域:http, server, location, location if

header_filter_by_lua 'lua code';
header_filter_by_lua_file path_file.lua;
作用:设置header 和 cookie;

lua_need_request_body on|off;
作用:是否读请求体,跟ngx.req.read_body()函数作用类似,但官方不推荐使用此方法。

lua_shared_dict shared_data 10m;
作用:设置一个共享全局变量表,在所有worker进程间共享。在lua脚本中可以如下访问它:
例:local shared_data = ngx.shared.shared_data
10m 不知是什么意思。

init_by_lua 'lua code';
init_by_lua_file lua_file.lua;
作用域:http
说明:ginx Master进程加载配置时执行;通常用于初始化全局配置/预加载Lua模块

init_worker_by_lua 'lua code';
init_worker_by_lua_file luafile.lua;
作用域:http

说明:每个Nginx Worker进程启动时调用的计时器,如果Master进程不允许则只会在init_by_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
init_by_lua            http
set_by_lua server, server if, location, location if
rewrite_by_lua http, server, location, location if
access_by_lua http, server, location, location if
content_by_lua location, location if
header_filter_by_lua http, server, location, location if
body_filter_by_lua http, server, location, location if
log_by_lua http, server, location, location if
{
set_by_lua: 流程分支处理判断变量初始化
rewrite_by_lua: 转发、重定向、缓存等功能(例如特定请求代理到外网)
access_by_lua: IP准入、接口权限等情况集中处理(例如配合iptable完成简单防火墙)
content_by_lua: 内容生成
header_filter_by_lua: 应答HTTP过滤处理(例如添加头部信息)
body_filter_by_lua: 应答BODY过滤处理(例如完成应答内容统一成大写)
log_by_lua: 会话完成后本地异步完成日志记录(日志可以记录在本地,还可以同步到其他机器)
}

1、output API(ngx.say和ngx.send_headers)

2、control API(ngx.exit和ngx.exec)

3、subrequest API(ngx.location.capture和ngx.location.capture_multi)

4、cosocket API(ngx.socket.tcp和ngx.req.socket)

header_filter_by_lua 不支持 1234
body_filter_by_lua 不支持 1234



#nginx_lua_doc
https://github.com/openresty/lua-nginx-module#status
#Nginx_lua_Doc_CN
https://moonbingbing.gitbooks.io/openresty-best-practices/openresty/sub_request.html

#安装Nginx

初始化 环境

1.14 安装 Lua + Cache + Image_filter + lua_status

1
hostnamectl set-hostname tj-lin-nginx-60v101

安装lib库

1
yum install -y wget make cmake gcc gcc-c++ autoconf automake libpng-devel libjpeg-devel zlib libxml2-devel ncurses-devel bison libtool-ltdl-devel libiconv libmcrypt mhash mcrypt libmcrypt-devel pcre-devel openssl-devel freetype-devel libcurl-devel gd-devel   lua-devel libexif-devel

停防水墙

1
2
3
4
5
6
7
8
9
10
11
12
13
14
systemctl stop firewalld
systemctl disable firewalld
systemctl disable firewalld

systemctl disable firewalld && systemctl stop firewalld && systemctl status firewalld


setenforce 0
sed -i "s/^SELINUX=enforcing/SELINUX=disabled/g" /etc/sysconfig/selinux
sed -i "s/^SELINUX=enforcing/SELINUX=disabled/g" /etc/selinux/config
sed -i "s/^SELINUX=permissive/SELINUX=disabled/g" /etc/sysconfig/selinux
sed -i "s/^SELINUX=permissive/SELINUX=disabled/g" /etc/selinux/config

getenforce

#导入yum资源

1
2
3
curl -o /etc/yum.repos.d/Centos-7.repo http://mirrors.aliyun.com/repo/Centos-7.repo 

curl -o /etc/yum.repos.d/epel-7.repo http://mirrors.aliyun.com/repo/epel-7.repo

#lua 安装lib

1
2
3
4
5
6
7
8
9
10
curl -O http://luajit.org/download/LuaJIT-2.0.5.tar.gz
tar xzvf LuaJIT-2.0.5.tar.gz
cd LuaJIT-2.0.5
make
make install
#注意环境变量!

export LUAJIT_LIB=/usr/local/luajit/lib

export LUAJIT_INC=/usr/local/luajit/include/luajit-2.0

Ngx_dev_Lua

1
curl -O https://github.com/simplresty/ngx_devel_kit/archive/v0.3.1rc1.tar.gz

Ngx_lua_stats 监控模块

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
 wget https://github.com/initial5/ngx-lua-stats/archive/master.zip
unzip master.zip
#
lua_shared_dict log_dict 20M;
lua_shared_dict result_dict 20M;
#
location / {
proxy_pass http://Node;
log_by_lua_file /usr/local/nginx/conf/lua/record.lua;
}
location /status {
content_by_lua_file /usr/local/nginx/conf/lua/output.lua;
}
location /empty_dict {
content_by_lua_file ./site-enable/empty_dict.lua;
}

Ngx_modele

1
wget https://github.com/openresty/lua-nginx-module/archive/v0.10.13.tar.gz

Nginx_image_modele

1
2
wget https://github.com/linsongze/ngx_http_image_filter_module/archive/master.zip
unzip master.zip

Ngx_Cache

1
2
wget http://labs.frickle.com/files/ngx_cache_purge-2.3.tar.gz
tar -zxvf ngx_cache_purge-2.3.tar.gz

nginx 1.14

1
2
3
4
5
6
7
8
9
10
11
12
wget http://nginx.org/download/nginx-1.14.0.tar.gz
tar -zxvf nginx-1.14.0.tar.gz


./configure --prefix=/usr/local/nginx --with-http_ssl_module --with-http_stub_status_module --with-http_realip_module --with-debug --add-module=/root/nginx/ngx_devel_kit-0.3.1rc1 --add-module=/root/nginx/lua-nginx-module-0.10.13 --add-module=/root/nginx/ngx_http_image_filter_module-master
make
make install


./configure --prefix=/usr/local/nginx --with-http_ssl_module --with-http_stub_status_module --with-http_realip_module --with-debug --add-module=/root/nginx/ngx_devel_kit-0.3.1rc1 --add-module=/root/nginx/lua-nginx-module-0.10.13 --add-module=/root/nginx/ngx_http_image_filter_module-master --add-module=/root/nginx//ngx_http_proxy_connect_module-master
make
make install

lua 错误处理

1
2
3
4
5
6
7
8
9
/usr/local/nginx-1.4.2/sbin/nginx -v
./objs/nginx: error while loading shared libraries: libluajit-5.1.so.2: cannot open shared object file: No such file or directory
解决方法:
# ln -s /usr/local/lib/libluajit-5.1.so.2 /lib64/libluajit-5.1.so.2

# /usr/local/nginx-1.4.2/sbin/nginx -v
./objs/nginx: error while loading shared libraries: libluajit-5.1.so.2: cannot open shared object file: No such file or directory
解决方法:
# ln -s /usr/local/lib/libluajit-5.1.so.2 /lib64/libluajit-5.1.so.2

启动脚本

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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
cat >  /usr/local/nginx/sbin/nginx.sh <<-EOF 
#!/bin/bash
# nginx Startup script for the Nginx HTTP Server
# it is v.0.0.2 version.
# chkconfig: - 85 15
# description: Nginx is a high-performance web and proxy server.
# It has a lot of features, but it's not for everyone.
# processname: nginx
# pidfile: /usr/local/nginx/logs/nginx.pid
# config: /usr/local/nginx/conf/nginx.conf
nginxd=/usr/local/nginx/sbin/nginx
nginx_config=/usr/local/nginx/conf/nginx.conf
nginx_pid=/usr/local/nginx/logs/nginx.pid
RETVAL=0
prog="nginx"
# Source function library.
. /etc/rc.d/init.d/functions
# Source networking configuration.
. /etc/sysconfig/network
# Check that networking is up.
[ "${NETWORKING}" = "no" ] && exit 0
[ -x $nginxd ] || exit 0
# Start nginx daemons functions.
start() {
if [ -e $nginx_pid ];then
echo "nginx already running...."
exit 1
fi
echo -n $"Starting $prog: "
daemon $nginxd -c ${nginx_config}
RETVAL=$?
echo
[ $RETVAL = 0 ] && touch /var/lock/subsys/nginx
return $RETVAL
}
# Stop nginx daemons functions.
stop() {
echo -n $"Stopping $prog: "
killproc $nginxd
RETVAL=$?
echo
[ $RETVAL = 0 ] && rm -f /var/lock/subsys/nginx /usr/local/nginx/logs/nginx.pid
}
# reload nginx service functions.
reload() {
echo -n $"Reloading $prog: "
#kill -HUP `cat ${nginx_pid}`
killproc $nginxd -HUP
RETVAL=$?
echo
}
# See how we were called.
case "$1" in
start)
start
;;
stop)
stop
;;
reload)
reload
;;
restart)
stop
start
;;
status)
status $prog
RETVAL=$?
;;
*)
echo $"Usage: $prog {start|stop|restart|reload|status|help}"
exit 1
exit $RETVAL
EOF
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
一、安装Nginx
useradd www -M -s /sbin/nologin
1、安装依赖:
yum install -y make cmake gcc gcc-c++ autoconf automake libpng-devel libjpeg-devel zlib libxml2-devel ncurses-devel bison libtool-ltdl-devel libiconv libmcrypt mhash mcrypt libmcrypt-devel pcre-devel openssl-devel freetype-devel libcurl-devel
2、下载nginx:
wget http://nginx.org/download/nginx-1.12.1.tar.gz
3、编译安装:
./configure --prefix=/usr/local/nginx --user=www --group=www --with-http_stub_status_module --with-http_ssl_module --with-http_realip_module --with-stream
添加第三方模块 --add-module=PATH

make make install clean

Nginx配置rsyslog

vim /usr/local/nginx/conf/nginx.conf
可以配置在http或者server段中,凡是可以配置access_log和error_log的位置都可以配置
# syslog表示使用syslog协议
# server=10.26.2.65 指明远程服务器地址,也可以指定本地
# facility=local7 指明设备管道使用local7
# tag=nginx 标签表示在日志文件中显示时候的标题
# severity=info 表示日志级别
access_log syslog:server=127.0.0.1,facility=local7,tag=nginx,severity=info;

vim /etc/rsyslog.conf
默认有下面的设置,会读取 /etc/rsyslog.d/*.conf 目录下的配置文件
$IncludeConfig /etc/rsyslog.d/*.conf
为nginx创建一个独立的配置文件
vim /etc/rsyslog.d/nginx.conf
$ModLoad imudp
$UDPServerRun 514
local7.* /var/log/nginx/access.log
&~
#如果不加下面的的&~则除了在/var/log/nginx/access.log中写入日志外,也会写入message文件 配置rsyslog的主配置文件,开启远程日志
# vim /etc/sysconfig/rsyslog
SYSLOGD_OPTIONS=”-c 2 -r -m 0″
#-c 2 使用兼容模式,默认是 -c 5
#-r 开启远程日志
#-m 0 标记时间戳。单位是分钟,为0时,表示禁用该功能

配置完成后重启nginx和rsyslog即可


系统优化:
user www;
worker_processes 8;
worker_rlimit_nofile 1048576;
#error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;

#pid logs/nginx.pid;



events {
worker_connections 102400;
multi_accept on;
use epoll;
}


http {
server_tokens off;
include mime.types;
default_type application/octet-stream;
client_header_buffer_size 32k;

keepalive_timeout 300s 300s;
keepalive_requests 10000;

# log_format main '$remote_addr - $remote_user [$time_local] $http_host "$request" '
# '$status $body_bytes_sent "$http_referer" '
# '"$http_user_agent" "$http_x_forwarded_for"'
# '$upstream_addr $upstream_response_time $request_time ';


# log_format json '{"@timestamp":"$time_iso8601",'
# '"@version":"1",'
# '"host":"$server_addr",'
# '"client":"$remote_addr",'
# '"size":"$body_bytes_sent",'
# '"responsetime":"$request_time",'
# '"domain":"$http_host",'
# '"request":"$request",'
# '"status":"$status",'
# '"upstream_addr":"$upstream_addr",'
# '"upstream_response_time":"$upstream_response_time",'
# '"request_time":"$request_time"'
# '}';
log_format main '$time_local $remote_addr $status $server_addr $http_host "$request" $body_bytes_sent $http_referer $http_user_agent $upstream_addr $request';
log_format main '$time_local $server_addr $status $http_host $request_uri $args $http_referer $http_user_agent $remote_addr $body_bytes_sent $request_method $upstream_addr $server_port';




# access_log /var/log/nginx/access.log main;
access_log syslog:server=127.0.0.1,facility=local1,tag=nginx,severity=info main;

sendfile on;
tcp_nopush on;
tcp_nodelay on;

#reset_timeout_connection on;
#limit_conn_zone $binary_remote_addr zone=addr:5m;
#limit_conn addr 100;
gzip on;
gzip_disable "msie6";
# gzip_static on;
gzip_proxied any;
gzip_min_length 1000;
gzip_comp_level 4;
gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript;

open_file_cache max=100000 inactive=20s;
open_file_cache_valid 30s;
open_file_cache_min_uses 2;
open_file_cache_errors on;
proxy_connect_timeout 300;
proxy_send_timeout 300;
proxy_read_timeout 300;
proxy_buffer_size 64k;
proxy_buffers 4 32k;
proxy_busy_buffers_size 64k;
proxy_temp_file_write_size 64k;
proxy_ignore_client_abort on;

server {
listen 80;
server_name localhost;



location /nginx_status {
stub_status on;
access_log off;
}

location / {
root html;
index index.html index.htm;
}

error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}


}
include /usr/local/nginx/conf/conf.d/*.conf;
}

net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_tw_recycle = 1
net.ipv4.tcp_fin_timeout = 30
net.ipv4.tcp_keepalive_time = 600

net.ipv4.ip_local_port_range = 1024 65000
net.ipv4.tcp_max_syn_backlog = 65535
net.ipv4.tcp_max_tw_buckets = 6000

net.ipv4.tcp_keepalive_probes = 5
net.ipv4.tcp_keepalive_intvl = 20

net.core.wmem_default = 8388608
net.core.rmem_default = 8388608
net.core.rmem_max = 873200
net.core.wmem_max = 873200

net.ipv4.tcp_rmem = 32768 436600 873200
net.ipv4.tcp_wmem = 8192 436600 873200

net.core.netdev_max_backlog = 32768

net.ipv4.tcp_timestamps = 0
net.ipv4.tcp_synack_retries = 2
net.ipv4.tcp_syn_retries = 2
net.ipv4.tcp_retries2 = 5

net.ipv4.tcp_mem = 41943040 73400320 94371840
net.ipv4.tcp_max_orphans = 3276800
fs.file-max = 1300000
net.ipv4.ip_nonlocal_bind=1



二、安装confd
直接拷贝confd到/usr/local/bin/
修改权限 chmod 755 /usr/local/bin/confd
mkdir -p /etc/confd/{conf.d,templates}
confd -version
vim /etc/confd/templates/account.tmpl
1) 80 443共存
{{range $dir := lsdir "/web/account.italent.cn"}}
upstream {{base $dir}} {
{{$custdir := printf "/web/account.italent.cn/%s/*" $dir}}{{range gets $custdir}}
server {{$data := json .Value}}{{$data.IP}}:80 {{$data.WEIGHT}};
{{end}}
}

server {
listen 80;
listen 443 ssl;
server_name {{base $dir}};
ssl_certificate /usr/local/nginx/certs/{{base $dir}}.crt;
ssl_certificate_key /usr/local/nginx/certs/{{base $dir}}.key;
access_log syslog:server=127.0.0.1,facility=local1,tag=nginx,severity=info;
access_log /var/log/nginx/{{base $dir}}.access.log;
error_log /var/log/nginx/{{base $dir}}.log;
location / {
proxy_pass http://{{base $dir}};
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
{{end}}
2) 80 强制跳转443
{{range $dir := lsdir "/web/account.italent.cn"}}
upstream {{base $dir}} {
{{$custdir := printf "/web/account.italent.cn/%s/*" $dir}}{{range gets $custdir}}
server {{$data := json .Value}}{{$data.IP}}:80 {{$data.WEIGHT}};
{{end}}
}

server {
listen 80;
server_name {{base $dir}};
return 301 https://$server_name$request_uri;
access_log syslog:server=127.0.0.1,facility=local1,tag=nginx,severity=info;
access_log /var/log/nginx/{{base $dir}}.access.log;
error_log /var/log/nginx/{{base $dir}}.log;
}

server {
listen 443 ssl;
server_name {{base $dir}};
ssl_certificate /usr/local/nginx/certs/{{base $dir}}.crt;
ssl_certificate_key /usr/local/nginx/certs/{{base $dir}}.key;
access_log syslog:server=127.0.0.1,facility=local1,tag=nginx,severity=info;
access_log /var/log/nginx/{{base $dir}}.access.log;
error_log /var/log/nginx/{{base $dir}}.log;
location / {
proxy_pass http://{{base $dir}};
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
{{end}}

vim /etc/confd/conf.d/account.toml
[template]
keys = [
"/web/account.italent.cn",
]
owner = "nginx"
mode = "0644"
src = "account.tmpl"
dest = "/usr/local/nginx/conf/conf.d/account.conf"


三、证书拷贝
/usr/local/nginx/certs