第 9 章 配置参考

Last Updated: 2026-12-04 09:44 Views: 22

全部选项的逐条参考(键、取值、默认、作用域与示例)见 docs/options-reference.md;本章为完整速查, 与源码解析器同步维护。

9.1 文件布局与格式

文件 内容
conf/wxserver.toml 主配置:全局、HTTP 默认、上游、stream、WAF、模块
conf/manager.toml 管理后台开关、监听、登录保护、JWT、用户密码哈希(0600)
conf/acme.toml ACME 申请与 DNS 凭据,0600,仅 master 读取
conf/cert.toml 证书库清单,站点通过 ssl.cert 引用
conf/vhost/*.toml 一站一文件,由 http.include 聚合
conf/certs/ 证书与私钥
conf/mime.toml、conf/*_params.toml、conf/waf/ 辅助配置(MIME 表、参数模板、WAF 规则/缓存)
  • include 两处作用域不同:顶层 include 引整段片段(可带 http/modules); http = { include = [...] } 聚合站点片段(片段根上直接写 servers/upstreams/map/geo/split_clients)。相对路径按各自被 include 文件目录解析;只允许配置目录内的相对 .toml(拒绝绝对路径、 ..、symlink 越界)。
  • manager.toml / acme.toml 是私有配置:主配置与任意 include 不得出现 manager / acme 顶层段(include = ["*.toml"] 也会被拒绝)。
  • 程序保存时输出 TOML 1.1 的 JSON 风格多行内联表;仅支持 TOML 1.0 的第三方 校验器可能误报,以 wxserver -t 为准。
  • 校验 wxserver -t -c <配置>;热重载 -s reload 或管理 API POST /api/config/reload。

9.2 global 全局块

键 类型/取值 默认 说明
user / group 字符串 平台默认 worker 运行账户;root 默认拒绝(调试需 WXSERVER_ALLOW_ROOT=1)
worker_processes 正整数 / "auto" 1 worker 数;"auto" 按并行度
worker_cpu_affinity "auto" / CPU id 数组 / cpumask 不绑定 Linux 逐 worker CPU 亲和
log_cpu_affinity CPU id 数组 不绑定 master 日志线程亲和(Linux)
pid 路径 run/wxserver.pid PID 文件,-s/服务管理依赖
shared_state 路径 run/wxserver.shm(默认启用) 跨 worker 共享状态文件(mmap,含上游 DNS 缓存);显式空串退回进程内状态;默认路径不可用告警回退
shared_state_size 大小 32m 共享状态文件大小(启用时生效)
log_socket 路径 run/wxserver-log.sock 多 worker 日志 IPC socket
log_queue_size 行数,0=同步写 有 access_log 1024,否则 64 日志队列长度;每槽约 320B;仅启动时生效
log_flush_interval_ms 毫秒 200 队列最长刷盘间隔;队列满时阻塞不丢行
server_tokens bool true false 隐藏版本号(旧 "on"/"off" 仍兼容)
graceful_timeout_sec 秒 30 优雅停机等待
error_page_root 目录 内置页面目录 file: 相对路径的查找根与安全边界(server > http > global)
log_redact / log_redact_keys bool / 数组 true / [] 访问日志 query 参数脱敏(password/token/secret/session/otp 等)
error_log 日志对象 未配置 path 时不输出 错误日志;作用域 global/server/location,见 §9.11

9.3 http 块

键 类型/取值 默认 说明
include glob 数组 [] 聚合站点片段
client_max_body_size 大小;"0" 不限 10m 请求体上限,server/location 可覆盖
sendfile bool true 静态零拷贝;仅明文 HTTP/1.1 静态响应生效
static_meta_cache_ms 毫秒 0 静态 stat 缓存 TTL
http2 / http3 bool 启用 false 为硬关闭,优先于站点级 true;实际开启由 listen 的 http2/http3 决定
ktls bool false Linux kTLS 卸载(AES-GCM),不支持自动回退
max_header_bytes 字节 1m 请求头上限(431)
read_header_timeout_sec 秒 30 读头超时
idle_timeout_sec 秒 75 keep-alive 空闲超时
access_log 路径/对象 未配置不记录 全局访问日志;关闭写 { enabled = false },见 §9.11
default_type MIME — 当前不被运行时消费,用站点/location 级
disabled_modules 模块名数组 [] 全局禁用模块(与站点列表合并)
gzip 对象 关闭 全局 gzip(见 §9.10)
error_page map 404→file:4xx.html,5xx→file:5xx.html 目标三形态 file:/root:/link:(继承 location > server > http)
servers / upstreams / map / geo / split_clients / proxy_cache_path 数组 — 站点/上游/变量派生/缓存区,见 §9.5–§9.7

proxy_cache_path 字段:name(必填)、path(配置后磁盘缓存,缺省进程内)、 max_size_mb(0=不限)、inactive_sec;单条缓存上限 16MB。

9.4 变量派生(map / geo / split_clients)

键 说明
map { name = "$x", source = "$y", default, hostnames, entries };键支持精确值、~正则、default;首个命中生效
geo { name = "$x", default, entries };键为 CIDR/裸 IP/default,最长前缀优先
split_clients { name = "$x", source = "$y", entries };键为 "N%",按 source 的 fnv 哈希落区间

9.5 server(站点)块

键 类型/取值 默认 说明
name 字符串 — 仅 Manager/转换器用于选择文件名 conf/vhost/{name}.toml;站点文件不保存,加载时以文件名为准
domain 数组;精确/*.x/x.*/* [] * 为默认站点
listen ":80" 或 { addr, ssl, http2, http3 } 必填 监听地址与协议开关
root / index 路径 / 数组 空 / ["index.html"] 站点根与索引
default_type MIME — 站点级 MIME 兜底
locations 数组 — location 列表,见 §9.6
ssl 对象 — 见 §9.13
error_page { "404" = "file:4xx.html" } 继承 http 级 状态码 → file:/root:/link: 目标
error_page_root 目录 继承 http/global 站点级 file: 相对路径根
access_log 路径/对象 继承 http 站点访问日志;关闭写 { enabled = false }
waf 对象 继承全局 站点级 WAF 覆盖
http2 / http3 / ktls / sendfile / client_max_body_size bool / 大小 继承 http 站点级覆盖
disabled_modules 数组 [] 站点级禁用模块
schedule 对象 不限制 定时开关:timezone(IANA)、open[](days/start/end)、reason、status(400-599,默认503)、page
strict_sni_host bool false Host 必须与 SNI 一致(否则 421)
https_redirect bool false 明文 308 到 https
limit_rate / limit_rate_after 大小 不限 站点级限速/免限速额度
disabled bool false 临时下线
rewrite 数组 [] rewrite 规则;条件用 cond(§9.6)

9.6 location 块

path 语法:= /exact 精确、/prefix/ 前缀、^~ /static/ 前缀跳过正则、 ~ / 与 ~* / 正则、@name 命名(仅内部进入)。优先级:exact > 最长前缀 (^~ 跳过正则)> 正则按顺序 > 最长前缀。

键 类型/取值 默认 说明
type static/proxy/fastcgi/uwsgi/scgi/grpc/memcached/concat/image/nchan/upload/return/redirect/mp4/empty_gif/stub_status/外置 static 内容处理器
root / alias 路径 继承站点 alias 替换 location 前缀;DAV 同样遵循
index / autoindex 数组 / bool ["index.html"] / false 目录索引(内部重定向进 index 命中的 location)/ 目录列表
default_type / internal MIME / bool — / false MIME 覆盖 / 仅内部重定向可进入
try_files 数组 [] 依序探测,末项 =code 或内部 URI;仅 $uri/ 匹配目录
disable_symlinks bool false docroot 下任一符号链接组件 → 403
return { code, url | text } — 返回/重定向/文本
error_page / access_log 同站点级 继承 覆盖站点级
client_max_body_size / limit_rate / limit_rate_after / sendfile 同上 继承 location 级覆盖
waf 对象 继承 location 级 WAF 开关

rewrite(server/location):无条件规则用 [pattern, replacement, flag]; 条件规则用对象 + cond。cond 为单个条件表或数组(AND)。主语: path + exists/is_file/is_dir/is_exec 布尔谓词,或 var + eq/ne/matches/not_matches/truthy,正则可加 ignore_case。 flag:last默认/break/redirect/permanent;flags = ["break"] 表示改写后停止后续 rewrite 规则;break = true 的规则停止后续规则且不改 URI。 替换串带 ? 丢原查询串,http(s):// 开头为外部跳转;内部重定向超 10 次 500。 旧的 if 块及条件 return/set/break 已移除。

9.7 upstream

键 类型/取值 默认 说明
name 字符串 必填 池名,proxy_pass = "http://名" 引用
lb round_robin/least_conn/ip_hash round_robin 调度算法
servers [{ addr, weight, max_fails, fail_timeout_sec, down }] 必填 weight 默认 0(视为 1)
keepalive 正整数 不保活 空闲连接池
health_check { type=http|tcp, uri, interval_sec=5, timeout_sec=3, falls=2, rises=2, expected_min_status=200 } 不启用 主动健康检查
sticky { cookie_name, path, expires_sec } 不启用 会话保持

运行时变更:POST/PATCH/DELETE /api/upstreams/<name>/servers…(persist:true 写回)。

9.8 stream 与 mail

stream(顶层 [stream],纯透传):upstreams[](name/servers); servers[]:listen(":port" 或 { addr, udp })、protocol(tcp/udp)、 proxy_pass(上游名/addr/$ssl_preread_server_name)、return(与 proxy_pass 二选一)、ssl_preread(读 ClientHello SNI)、sni(域名→{ proxy_pass } 分流)、 proxy_connect_timeout_sec(默认 5)。SSL 终止/访问日志/连接限数未实现。

mail(顶层 [mail]):servers[]:listen(必填)、proxy_pass(必填)、 proxy_protocol(默认 false,发送 PROXY v1)、timeout_sec(默认 60,读写刷新)。 name/protocol 键当前被忽略(纯 TCP 透传);上游连不上直接断开。

9.9 waf 块

键 类型/取值 默认 说明
enabled bool false 站点/location 的 waf 可覆盖关闭
engine full/fast full full=SecRule/CRS 引擎;fast=轻量参数/签名检测(不编译规则)
rules [{ id, name, pattern, is_regex, caseless, targets, action, comment }] [] targets:URI/ARGS/HEADERS/BODY/COOKIE/UA/REFERER/IP;action:block/allow/log;allow 短路 CRS
response_rules 数组(仅 block) [] 响应体检测,命中 403 + X-WAF-Blocked
response_body_limit 字节 1m 响应检测缓冲上限
ip_lists(别名 ip_blacklist/ip_whitelist) { white, black } 空 白名单放行、黑名单 403
cc { enabled, window_sec=60, max_requests=600, key=ip|ip+uri|ip+ua|$变量, block_sec=60, log_interval_sec=30 } 关闭 CC 防护;log_interval_sec 为拦截日志抑制窗口
crs bool false 加载 CRS:磁盘 conf/waf/crs.toml 优先,否则内置 crs-lite
rules_files / rules_text TOML 路径数组 / SecRule 文本 — 完整 CRS 经 wxserver-convert -from crs 转 TOML
paranoia_level / inbound_anomaly_threshold / outbound_anomaly_threshold 整数 1 / 5 / 4 CRS 调参
rule_exclusions ID 数组 [] 按 ID 排除误报
skip_unsupported_rules bool false 跳过不支持的指令

自定义规则先于 CRS 执行;站点规则 ID 段 1000000+、全局 100000+。 @rx 规则预编译为共享 DFA 缓存(conf/waf/cache/,WXSERVER_WAF_CACHE=0 禁用)。

9.10 模块指令速查

键写在 location(或 http/server 层),或 modules.<模块名> 表;完整语义见 docs/options-reference.md。

模块 主要键(默认) 说明
proxy proxy_pass(必填)、proxy_set_header、proxy_hide_header、proxy_intercept_errors、proxy_redirect、proxy_next_upstream{http_codes,timeout}、proxy_next_upstream_tries、proxy_buffering_off、proxy_connect/read_timeout_sec(5⁄60)、proxy_cache、proxy_cache_valid 反向代理;Upgrade+Connection 双头启用 WS 隧道;上游失败 502⁄504 渲染错误页(error_page 优先,内置 5xx 兜底),细节写 error.log;域名/容器名由 master 定期解析并缓存,worker 连接失败时重取
fastcgi fastcgi_pass(必填)、fastcgi_param(s)、fastcgi_params_file、fastcgi_index、fastcgi_split_path_info、fastcgi_hide_header、fastcgi_intercept_errors、fastcgi_keep_conn(false)、fastcgi_keep_conn_max(1)、fastcgi_keep_conn_idle_sec(15)、fastcgi_*_timeout_sec(5/60/60)、fastcgi_check_script(true) PHP;REQUEST_URI 恒为原始 URI;keepalive 默认关闭以免占满 PHP-FPM pm.max_children;fastcgi_pass 域名由 master 每 5 分钟解析并写入 shared_state,worker 失败时重取(Unix socket 不解析)
uwsgi/scgi <p>_pass(必填)、<p>_param、<p>_params_file、<p>_connect/read_timeout_sec(5⁄60)、modifier1(0) UWSGI/SCGI 协议;域名由 master 解析并缓存
grpc grpc_pass(必填)、grpc_tls、grpc_tls_server_name/ca/client_cert/client_key、grpc_*_timeout_sec(5⁄60)、grpc_intercept_errors h2 透传,grpc-status 走 trailer;域名由 master 解析并缓存(TLS SNI 仍用域名)
memcached memcached_pass(必填)、memcached_key($host$request_uri)、memcached_content_type、超时(5⁄10) 只允许 GET/HEAD;未命中 404;域名由 master 解析并缓存,不支持 Unix socket
staticfile root/alias/index/autoindex/try_files/disable_symlinks、gzip_static/brotli_static/zstd_static、dav{methods,create_full_put_path} WebDAV RFC 4918;预压缩 br>zstd>gzip
rewrite rewrite[[pat,repl,flag]]、对象 + cond、set、return flag 默认 last
limit limit_req{rate,burst=0,key,status=503}、limit_conn{limit,key,status=503} shared_state 默认启用,计数开箱跨 worker
access access{rules[{action,cidr}],default=deny} 某层配置替换上层
auth_basic auth_basic{realm,users_file,users} htpasswd 兼容
auth_request auth_request{url,method=GET,timeout_ms=3000,allow_codes=[200],deny_codes=[401,403],copy_headers} 外部鉴权子请求
auth_jwt auth_jwt{alg=HS256,secret,key_file,jwks_uri,leeway_sec=30,claims,realm} HS256/RS256/ES256
secure_link secure_link{secret,md5_arg,expires_arg,require=true} MD5(base64url) 签名 URL
referer referer{valid,invalid_status=403} 防盗链
realip realip{from,header=X-Forwarded-For,mode=recursive} recursive 从右跳过可信代理
userid / browser / geoip userid{name,path,expires,domain}、browser{modern,ancient,deny_ancient}、geoip{db,on} 变量 $uid/$modern_browser/$geoip_*
headers headers{expires,add_headers,add_headers_always,set_headers,more_set_headers,more_clear_headers,more_headers,clear_headers} add 某层替换上层;more_* 父层先执行
security_headers security_headers{enabled,hsts,hsts_plaintext,csp,x_frame_options,referrer_policy,permissions_policy,nosniff} 默认关闭;逐字段合并
gzip/gunzip gzip{on,level=6,min_length=20,types,vary=true,proxied=true,disable,no_compression_4xx}、gunzip{on} 只压 200/403/404
brotli/zstd brotli{on,level=5,min_length=256}、zstd{on,level=3,min_length=256} 动态优先 br>gzip>zstd
sub/addition/ssi/charset/minify sub{patterns[{search,replace}],once,types}、addition{before,after,types}、ssi{on,types,limit=8m}、charset{charset,source_charset,override_charset,charset_types}、minify{on,types,max_size=256k} 响应体处理
image_thumb image_thumb{quality=75,cache,backend,types,default_mode,water{...},watermark_text} URL !c300x200.jpg
nchan nchan{channel,mode=pubsub,buffer=16,history,max_subscribers=1024,max_message=256k,poll_timeout_sec=30,heartbeat_sec=15,cors} SSE/WS/长轮询
upload upload{dir=run/uploads,max_size=1g,cors} tus 1.0
mirror mirror{targets,copy_body=false} 异步镜像
accesslog/logsink access_log(对象见 §9.11)、modules.http_logsink{protocol=udp,addr,url,format=json,timeout_ms=1000} 远程日志 sink
error_guard modules.http_error_guard{enabled,window_sec=60,threshold=20,block_sec=300,status=429,count_codes,count_5xx,key,whitelist} 错误率封禁
sysguard modules.http_sysguard{enabled,max_load1,min_mem_available_mb,status=503,retry_after=5} 过载保护

fastcgi 默认会向 PHP 传递 SCRIPT_FILENAME、QUERY_STRING、REQUEST_METHOD、HTTP_*、SERVER_ADDR、REMOTE_PORT、REDIRECT_STATUS 等变量;HTTP/2、HTTP/3 请求没有 Host 头时,HTTP_HOST 由 :authority 补齐;多个 Cookie 请求头按 "; " 合并(否则 PHP 只能取到第一个 cookie,WordPress 登录/会话会失效)。

9.11 日志对象(error_log / access_log 通用)

字段 类型/取值 默认 说明
path 路径,支持 $year/$month/$day 未配置(不输出) 相对工作目录;配绝对路径时 logs/ 前缀映射到该目录;off/- 会被校验拒绝,关闭用 enabled = false
level debug/info/warn/error warn 仅 error_log
enabled bool true false 完全关闭该层 error_log/access_log(不落盘、不写 stderr、不发 sink);下层可重新启用;跨平台替代 /dev/null
console bool false 仅 error_log:额外写 stderr/journal;enabled = false 优先
max_size_mb / max_backups 整数 0 按大小轮转/保留份数
encrypt / key_file bool / 路径 false 逐行 AES-256-GCM(WXE1:),Manager 读取自动解密
format text/binary text binary 为 .wxlog(wxserver-log 读取)
format_template 模板 combined 仅文本格式
sample 正整数 1 每 N 条记 1 条

9.12 manager.toml

键 类型/取值 默认 说明
enable bool false 启用管理后台
listen host:port 127.0.0.1:9090 非 loopback 必须配 [tls] 或 allow_http=true
tls { cert } 引用证书库或 { cert_file, key_file } — Manager 自身 TLS
allow_cidr CIDR/裸 IP 数组 [] 来源白名单,按 TCP 对端判断;未命中 403
trust_proxy / proxy_cidr bool / CIDR 数组 false / [] trust_proxy 必须配非空 proxy_cidr(fail closed);默认拒绝带 X-Forwarded-*/Via/Forwarded 头的请求(403)
domain 主机名数组 [] Host 校验,不匹配 421
allow_http bool false 显式允许明文非 loopback
users [{ name, password_hash }] 首启自动建 admin bcrypt
jwt { secret_file=run/jwt.secret, expire_sec=86400 } — 会话令牌
login { max_fail, window_sec, block_sec, captcha_after, captcha_ttl } — 登录失败封禁与验证码
totp 系统维护 — 2FA 状态在 run/manager-totp.json(0600),不手编

9.13 acme.toml 与 ssl

[certs.<name>]:domains(必填)、email、challenge(auto/http/dns)、 directory/staging、timeout_sec=60、auto_renew=true、renew_before_days=30、 check_interval_hours=12、key_type=ec256、eab_kid/eab_hmac_key、 must_staple、preferred_chain、on_demand、request_timeout_sec=30(1-180)、 dns{provider=cloudflare|alidns|tencentcloud|route53, credentials, api_base, ttl_sec=120, propagation_timeout_sec=120, propagation_delay_sec, resolvers, proxy}。

站点 ssl:cert(证书库名)或 cert_file/key_file、protocols (TLS1.2⁄1.3)、ciphers、session_cache、client_cert_file/verify_client/ verify_depth(mTLS)、prefer_server_ciphers。

9.14 变量参考

内建:$uri $document_uri $request_uri $args $query_string $host $server_name $http_host $http_<header> $scheme $https $server_port $request_method $server_protocol $remote_addr $client_ip $binary_remote_addr $remote_user $document_root $content_length $content_type $is_args $internal_redirect,以及 $arg_*、$cookie_*。 模块注册:$jwt_claim_*/$jwt_error、$secure_link/$secure_link_expires、 $uid、$modern_browser/$ancient_browser、$geoip_*、rewrite set 与 map/geo/split_clients 派生变量。解析顺序:内建 → 模块 → 派生。

9.15 命令行与转换

wxserver -c <配置>            # 前台启动
wxserver -t -c <配置>         # 校验
wxserver -s reload|stop|quit  # 信号控制
wxserver -no-manager          # 禁用管理后台
wxserver --service install|uninstall|start|stop|restart|status
wxserver --reset-password [pwd] / --reset-totp
wxserver-convert -from auto|nginx|apache|htaccess|crs -in <file> [-out <file>] [--split-vhosts conf/vhost]
wxserver-tool htpasswd / bench / precompress / toml

wxserver-convert 文件模式展开 include;--split-vhosts 把每个站点拆到 conf/vhost/{name}.toml;.htaccess 自动识别输出可粘贴的 location 片段; 未识别指令以 warning 输出(-quiet 静默)。工具详解见第 7 章。

← Previous Article 第 8 章 模块 Next Article → 第 10 章 故障排查

Comments

No comments yet