OpenResty 配置IP黑白名单限制

OpenResty® 是一个基于 Nginx 与 Lua 的高性能 Web 平台,其内部集成了大量精良的 Lua 库、第三方模块以及大多数的依赖项。用于方便地搭建能够处理超高并发、扩展性极高的动态 Web 应用、Web 服务和动态网关。

OpenResty® 通过汇聚各种设计精良的 Nginx 模块(主要由 OpenResty 团队自主开发),从而将 Nginx 有效地变成一个强大的通用 Web 应用平台。这样,Web 开发人员和系统工程师可以使用 Lua 脚本语言调动 Nginx 支持的各种 C 以及 Lua 模块,快速构造出足以胜任 10K 乃至 1000K 以上单机并发连接的高性能 Web 应用系统。

OpenResty® 的目标是让你的Web服务直接跑在 Nginx 服务内部,充分利用 Nginx 的非阻塞 I/O 模型,不仅仅对 HTTP 客户端请求,甚至于对远程后端诸如 MySQL、PostgreSQL、Memcached 以及 Redis 等都进行一致的高性能响应。

openresty 服务编译部署

服务编译

首先,可以根据下面的示例安装和构建OpenResty。

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
# 1. 安装所有依赖
yum install -y gcc make pcre-devel openssl-devel zlib-devel readline-devel ncurses-devel pcre-devel openssl-devel zlib-devel

# 2. 下载 OpenResty
wget https://openresty.org/download/openresty-1.25.3.1.tar.gz
tar -xzvf openresty-1.25.3.1.tar.gz
cd openresty-1.25.3.1

# 3. 配置./configure(关键编译选项)
./configure \
--prefix=/opt/openresty \
--user=nginx --group=nginx \
--with-luajit \
--with-pcre-jit \
--with-threads \
--with-file-aio \
--with-http_ssl_module \
--with-http_v2_module \
--with-http_realip_module \
--with-http_stub_status_module \
--with-http_gzip_static_module \
--with-http_sub_module \
--with-http_auth_request_module \
--with-stream \
--with-stream_ssl_module \
--with-stream_ssl_preread_module \
--with-stream_realip_module \
--with-compat \
--with-cc-opt="-O2 -fstack-protector-strong -D_FORTIFY_SOURCE=2" \
--with-ld-opt="-Wl,-z,relro,-z,now"

# 4. 编译安装
make -j$(nproc)
make install

# 5. 验证
/opt/openresty/nginx/sbin/nginx -V
nginx version: openresty/1.25.3.1
built by gcc 7.3.0 (GCC)
built with OpenSSL 1.1.1f 31 Mar 2020
TLS SNI support enabled
configure arguments: --prefix=/opt/openresty/nginx --with-cc-opt='-O2 -O2 -fstack-protector-strong -D_FORTIFY_SOURCE=2' --add-module=../ngx_devel_kit-0.3.4 --add-module=../echo-nginx-module-0.64 --add-module=../xss-nginx-module-0.07 --add-module=../ngx_coolkit-0.2 --add-module=../set-misc-nginx-module-0.33 --add-module=../form-input-nginx-module-0.12 --add-module=../encrypted-session-nginx-module-0.09 --add-module=../srcache-nginx-module-0.33 --add-module=../ngx_lua-0.10.31rc5 --add-module=../ngx_lua_upstream-0.08 --add-module=../headers-more-nginx-module-0.39 --add-module=../array-var-nginx-module-0.06 --add-module=../memc-nginx-module-0.20 --add-module=../redis2-nginx-module-0.15 --add-module=../redis-nginx-module-0.41 --add-module=../rds-json-nginx-module-0.17 --add-module=../rds-csv-nginx-module-0.10 --add-module=../ngx_stream_lua-0.0.19rc4 --with-ld-opt='-Wl,-rpath,/opt/openresty/luajit/lib -Wl,-z,relro,-z,now' --user=nginx --group=nginx --with-pcre-jit --with-threads --with-file-aio --with-http_ssl_module --with-http_v2_module --with-http_realip_module --with-http_stub_status_module --with-http_gzip_static_module --with-http_sub_module --with-http_auth_request_module --with-stream --with-stream_ssl_module --with-stream_ssl_preread_module --with-stream_realip_module --with-compat --with-stream

优化:隐藏openresty版本号

1
2
3
4
5
http {
server_tokens off;
# 用 headers_more(OpenResty 自带)干掉 Server 头
more_clear_headers 'Server';
}

公网 + 监控 + Lua 场景的编译参数说明

参数作用
--with-luajitSkyWalking Nginx-Lua、Prometheus Lua 客户端都依赖 LuaJIT,性能差 5~10 倍
--with-pcre-jit公网请求正则匹配(路由、WAF、日志解析)极多,JIT 必开
--with-http_ssl_module公网强制 HTTPS
--with-http_v2_module现代浏览器/客户端走 h2,需配合 SSL
--with-http_realip_module前面有 CDN/SLB 时必须拿真实客户端 IP,监控和限流都靠它
--with-http_stub_status_module最轻量的 Nginx 自身状态(连接数/请求数),Prometheus nginx-prometheus-exporter 可抓,或自己 Lua 暴露
--with-threads + --with-file-aio公网网关若兼做静态资源/大响应体,线程池避免阻塞 event loop;纯反向代理不命中文件 IO 也无害
--with-http_gzip_static_module预压缩 .gz 直发,省 CPU
--with-http_sub_module响应体脱敏(如把内部报错信息替换掉再返回公网)
--with-http_auth_request_module微服务网关统一鉴权子请求
--with-stream* + ssl_preread公网 TCP/TLS 透传、按 SNI 路由、stream 层真实 IP
--with-compat以后要装动态模块(如 brotli)不冲突
--user=nginx --group=nginx不以 root 跑 worker,降攻击面
-fstack-protector-strong 等编译期栈保护,公网边界机建议开

采集 openresty 监控数据

配置 SkyWalking 链路追踪

下载拿源码(不需编译)

1
2
3
4
cd /usr/local/openresty
wget https://mirrors.tuna.tsinghua.edu.cn/apache/skywalking/nginx-lua/1.0.1/skywalking-nginx-lua-1.0.1-src.tgz
tar xzf skywalking-nginx-lua-1.0.1-src.tgz
mv skywalking-nginx-lua-1.0.1 skywalking-nginx-lua

目录:/opt/openresty/lua/skywalking-nginx-lua/lib/?.lua

nginx.conf http 块加

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
http {
lua_package_path "/usr/local/openresty/skywalking-nginx-lua/lib/?.lua;;";

lua_shared_dict tracing_buffer 100m;

init_worker_by_lua_block {
local metadata_buffer = ngx.shared.tracing_buffer
metadata_buffer:set('serviceName', 'openresty-gateway')
metadata_buffer:set('serviceInstanceName', 'openresty-01')
require("skywalking.util").set_randomseed()
require("skywalking.client"):startBackendTimer("http://skywalking-oap:12800")
skywalking_tracer = require("skywalking.tracer")
}

server {
listen 80;
location /api/ {
rewrite_by_lua_block {
skywalking_tracer:start("backend-service")
}
proxy_pass http://backend;
body_filter_by_lua_block {
if ngz.arg[2] then skywalking_tracer:finish() end
}
log_by_lua_block {
skywalking_tracer:prepareForReport()
}
}
}
}

重启 openresty 即可,链路数据走 HTTP 上报到 OAP,无需重编。


配置 Prometheus(nginx-lua-prometheus)

下载 Lua 库(不需编译)

1
2
3
4
cd /opt/openresty/lua/
opm get knyar/nginx-lua-prometheus
# 或手动 git clone,把 prometheus.lua 放到
# git clone https://github.com/knyar/nginx-lua-prometheus.git /opt/openresty/lua/nginx-lua-prometheus

目录:/opt/openresty/lua/skywalking-nginx-lua/lib/?.lua

nginx.conf http 块加

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
http {
lua_shared_dict prometheus_metrics 100m;
lua_package_path "/opt/openresty/lua/nginx-lua-prometheus/?.lua;;";

init_worker_by_lua_block {
prometheus = require("prometheus").init("prometheus_metrics")
metric_requests = prometheus:counter(
"nginx_http_requests_total", "Number of HTTP requests", {"host", "method", "status"})
metric_latency = prometheus:histogram(
"nginx_http_request_duration_seconds", "HTTP request latency", {"host"})
metric_connections = prometheus:gauge(
"nginx_http_connections", "Number of HTTP connections", {"state"})
}

log_by_lua_block {
metric_reqs:inc(1, {ngx.var.server_name, ngx.var.status:sub(1,1).."XX"})
metric_lat:observe(tonumber(ngx.var.request_time), {ngx.var.server_name})
}

server {
listen 9145;
allow 192.168.0.0/16;
deny all;

location /metrics {
content_by_lua_block {
prometheus:collect()
}
}
}
}

Prometheus 侧抓 http://openresty:9145/metrics 即可。

openresty 相关参数

以下是整理的 OpenResty ./configure 全量参数清单(基于 1.25.3.x / 1.27.x,覆盖 Nginx 原生参数 + OpenResty 扩展参数),按类别整理。

基础与路径类(Nginx 原生)

参数说明
--help / -h打印帮助
--prefix=PATH安装根目录,默认 /usr/local/openresty
--sbin-path=PATHnginx 二进制路径
--conf-path=PATHnginx.conf 路径
--error-log-path=PATH错误日志路径
--pid-path=PATHpid 文件路径
--lock-path=PATHlock 文件路径
--user=NAMEworker 运行用户(建议 nginx)
--group=NAMEworker 运行组
--build=NAME自定义 build 名(nginx -V 可见)
--builddir=PATH编译临时目录

编译工具链类

参数说明
--with-cc=PATH指定 C 编译器
--with-cc-opt="..."C 编译选项(如 -O2 -fstack-protector-strong)
--with-ld-opt="..."链接选项(如 -Wl,-z,relro,-z,now)
--with-debug开启 debug 日志(性能下降,排错用)
--with-no-pool-patch关闭 nginx 内存池,排查 Lua 内存泄漏用
--with-dtrace-probes开启 DTrace USDT 探针
--with-dtrace=PATH指定 dtrace 路径
-jN并行编译(传给 make)

依赖库静态编译类

参数说明
--with-pcre=DIR指定 PCRE 源码目录(静态编入)
--with-pcre-jit开启 PCRE JIT(正则性能关键)
--with-pcre-opt=OPTSPCRE 编译附加选项
--with-openssl=DIR指定 OpenSSL 源码目录
--with-openssl-opt=OPTSOpenSSL 编译附加选项
--with-zlib=DIR指定 zlib 源码目录
--with-zlib-opt=OPTSzlib 编译附加选项
--with-libdrizzle=DIRdrizzle 库路径(mysql 客户端模块用)
--with-libpq=DIRPostgreSQL 库路径
--with-pg_config=PATHpg_config 路径

生产建议:能用系统 pcre-devel/openssl-devel/zlib-devel 就用系统包;离线环境才用 --with-xxx=源码目录。


Nginx 核心 HTTP 模块(默认开,可 --without- 关)

参数说明
--without-http彻底关闭 HTTP 服务
--without-http-cache关闭 upstream 缓存
--without-http_charset_module字符集转换
--without-http_gzip_modulegzip 输出
--without-http_ssi_moduleSSI 包含
--without-http_userid_moduleuserid 下发
--without-http_access_moduleallow/deny
--without-http_auth_basic_modulebasic 认证
--without-http_mirror_module流量镜像
--without-http_rewrite_modulerewrite(关掉后 PCRE 仍可被其他模块用)
--without-http_proxy_moduleproxy_pass
--without-http_fastcgi_moduleFastCGI
--without-http_uwsgi_moduleuWSGI
--without-http_scgi_moduleSCGI
--without-http_grpc_modulegRPC 代理
--without-http_memcached_modulememcached
--without-http_limit_conn_module限连接
--without-http_limit_req_module限请求
--without-http_autoindex_module目录浏览
--without-http_geo_modulegeo 变量
--without-http_map_modulemap 指令
--without-http_split_clients_module分流
--without-http_referer_modulereferer 检查
--without-http_upstream_*_module各类 upstream 负载算法

Nginx 可选 HTTP 模块(--with- 开启,默认关)

参数说明公网网关建议
--with-http_ssl_moduleHTTPS✅ 必开
--with-http_v2_moduleHTTP/2✅ 必开
--with-http_v3_moduleHTTP/3可选(需 OpenSSL 支持)
--with-http_realip_module取真实 IP✅ 必开
--with-http_stub_status_module基础状态页✅ 必开
--with-http_gzip_static_module预压缩 .gz 直发✅ 建议
--with-http_sub_module响应体替换✅ 建议(脱敏)
--with-http_auth_request_module子请求鉴权✅ 网关建议
--with-threads线程池✅ 建议
--with-file-aio异步文件 IO✅ 建议
--with-http_addition_module响应前后追加❌ 少用
--with-http_xslt_module[=dynamic]XML 转换❌
--with-http_image_filter_module[=dynamic]图片处理❌
--with-http_geoip_module[=dynamic]GeoIP❌ 用 Lua 替代
--with-http_dav_moduleWebDAV❌ 公网禁用
--with-http_flv_moduleFLV 伪流❌
--with-http_mp4_moduleMP4 伪流❌
--with-http_gunzip_module服务端 gunzip❌
--with-http_random_index_module随机首页❌
--with-http_secure_link_module防盗链可选
--with-http_degradation_module内存降级可选
--with-http_slice_module大文件分片可选(CDN 场景)
--with-http_perl_module[=dynamic]Perl 嵌入❌

Stream(TCP/UDP)模块

参数说明公网网关
--with-stream[=dynamic]四层代理✅ 建议
--with-stream_ssl_modulestream SSL✅ 建议
--with-stream_ssl_preread_moduleSNI 预读路由✅ 建议
--with-stream_realip_module取真实 IP✅ 建议
--with-stream_geoip_module[=dynamic]GeoIP❌
--without-stream_limit_conn_module四层限连可选关
--without-stream_map_module 等同 HTTP 类按需

Mail 模块(基本不用)

参数说明
--with-mail[=dynamic]POP3/IMAP/SMTP 代理
--with-mail_ssl_module邮件 SSL
--without-mail_pop3_module 等关闭子协议

网关场景一律不加 --with-mail。


OpenResty 专属参数(重点)

LuaJIT / Lua

参数说明
--with-luajit编入内置 LuaJIT 2.1(默认开)
--with-luajit=DIR用外部 LuaJIT
--with-luajit-xcflags=LuaJIT 编译参数
--with-luajit-ldflags=LuaJIT 链接参数
--without-luajit-lua52关 Lua 5.2 兼容扩展
--without-luajit-gc64关 GC64(x86_64 默认开)
--with-lua51编入标准 Lua 5.1(不推荐)
-jN并行编 LuaJIT

OpenResty 自带 Lua/Nginx 模块(默认开,可 --without- 禁)

  • --without-http_lua_module
  • --without-http_lua_upstream_module
  • --without-stream_lua_module
  • --without-ngx_devel_kit_module
  • --without-http_echo_module
  • --without-http_xss_module
  • --without-http_coolkit_module
  • --without-http_set_misc_module
  • --without-http_form_input_module
  • --without-http_encrypted_session_module
  • --without-http_srcache_module
  • --without-http_headers_more_module
  • --without-http_array_var_module
  • --without-http_memc_module
  • --without-http_redis2_module
  • --without-http_redis_module
  • --without-http_rds_json_module / --without-http_rds_csv_module

OpenResty 自带 Lua 库(默认带,可 --without-lua_resty_* 禁)

  • --without-lua_cjson
  • --without-lua_resty_core
  • --without-lua_resty_redis
  • --without-lua_resty_mysql
  • --without-lua_resty_dns
  • --without-lua_resty_lrucache
  • --without-lua_resty_lock
  • --without-lua_resty_limit_traffic
  • --without-lua_resty_websocket 等

可选额外模块

  • --with-http_iconv_module:编码转换
  • --with-http_drizzle_module:直连 MySQL
  • --with-http_postgres_module:直连 PG

公网网关「记录用」推荐基线

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
./configure \
--prefix=/opt/openresty \
--user=nginx --group=nginx \
--with-luajit \
--with-pcre-jit \
--with-threads \
--with-file-aio \
--with-http_ssl_module \
--with-http_v2_module \
--with-http_realip_module \
--with-http_stub_status_module \
--with-http_gzip_static_module \
--with-http_sub_module \
--with-http_auth_request_module \
--with-stream \
--with-stream_ssl_module \
--with-stream_ssl_preread_module \
--with-stream_realip_module \
--with-compat \
--with-cc-opt="-O2 -fstack-protector-strong -D_FORTIFY_SOURCE=2" \
--with-ld-opt="-Wl,-z,relro,-z,now"

显式关闭(缩小攻击面):

1
2
3
4
5
6
--without-http_dav_module \
--without-http_autoindex_module \
--without-http_ssi_module \
--without-mail_pop3_module \
--without-mail_imap_module \
--without-mail_smtp_module

一句话记忆法

  • 路径类:--prefix 系列
  • 依赖类:--with-pcre/openssl/zlib(或 -devel 系统包)
  • HTTP 必开:ssl / v2 / realip / stub_status
  • HTTP 选开:threads / file-aio / gzip_static / sub / auth_request
  • Stream 选开:stream / stream_ssl / ssl_preread / realip
  • OpenResty 灵魂:--with-luajit(SkyWalking/Prometheus Lua 都靠它)
  • 公网别开:dav / xslt / image_filter / geoip / flv / mp4 / mail / perl

以上参数覆盖 ./configure --help 的 95% 以上内容,剩下少量平台相关(select/poll/kqueue)Linux 生产用不到,可不记。

-------------本文结束感谢您的阅读-------------