第 9 章 設定參考

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

全部選項的逐條參考(鍵、取值、預設、作用域與範例)見 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 預設會傳遞 SCRIPT_FILENAME、QUERY_STRING、REQUEST_METHOD、HTTP_*、SERVER_ADDR、REMOTE_PORT、REDIRECT_STATUS 等變數給 PHP;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:),管理後臺讀取時自動解密
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 } — 管理後臺自身 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