sgcProxy

User Guide

Version 2026.12.0
2026-12-08
eSeGeCe, https://www.esegece.com
Copyright © 2026 eSeGeCe

This guide is also available as a PDF: sgcProxy-Help.pdf. Product page: sgcProxy.

1Introduction

sgcProxy is a reverse proxy in the style of nginx. It accepts HTTP/1.1, HTTP/2 and HTTP/3 connections from clients, picks a virtual server by host name, picks a location by path, and then forwards the request to your backend servers, serves a static file or answers it directly.

sgcProxy is a single executable for 64 bit Windows and 64 bit Linux. On Windows it runs as a Windows service, on Linux as a systemd daemon. One JSON file holds the whole configuration. The key names follow nginx where they can, so an nginx setup maps onto sgcProxy almost key by key.

Features

  • Virtual servers chosen by the Host header or the TLS SNI name: exact names, wildcard names, suffix names, regular expressions and a default server per address and port.
  • nginx location matching: exact (=), prefix, ^~ prefix and regular expressions, with secure URI normalization (percent decoding, strict UTF-8, merged slashes, dot segments).
  • Reverse proxy to a URL or to a named upstream group: streamed request and response bodies, upstream keep-alive connections, retries, timeouts, X-Forwarded-For, X-Forwarded-Proto, X-Forwarded-Host, proxy_set_header and proxy_hide_header.
  • Load balancing with smooth weighted round robin, least connections, IP hash and hash (also consistent), backup and down servers, passive health and active health checks.
  • TLS with the native engine (TLS 1.3 and 1.2) or OpenSSL 3, the certificate of each server picked by SNI, the post-quantum hybrid group X25519MLKEM768 first in the default list, session tickets and HSTS.
  • HTTP/2 and HTTP/3 to the clients of TLS listeners, with Alt-Svc for HTTP/3.
  • Automatic certificates with ACME (RFC 8555): HTTP-01 and TLS-ALPN-01 challenges, renewal by ACME Renewal Information (RFC 9773).
  • Static files: index, try_files, autoindex, MIME types, ETag and Last-Modified, byte ranges and expires.
  • gzip compression of static, proxied and generated responses, flushed per write so server-sent events still stream.
  • A proxy cache on disk (RFC 9111) with revalidation, miss collapsing, stale answers and a purge endpoint.
  • WebSocket proxying, where an idle tunnel holds no thread.
  • Firewall: allow and deny lists, trusted proxies, a WAF for SQL injection, XSS, path traversal and command injection, flood protection and GeoIP. Rate limits with token bucket, sliding window or fixed window.
  • A status page (JSON) and Prometheus metrics on a local admin listener.
  • Error log in the nginx line format, access log in combined or JSON format. Warn and error lines also go to the Windows event log.
  • Strict validation with --test, a hot reload that keeps the running configuration when the new one is invalid, and a graceful drain on stop.
  • Event driven forwarding of proxied HTTP/1.1 requests on IOCP (Windows) and EPOLL (Linux), so a request in flight holds no thread.

System requirements

  • Windows: 64 bit Windows 10, Windows Server 2016 or later. Setup needs administrator rights.
  • Linux: a 64 bit Linux distribution with systemd. The installer runs as root.

Licence

sgcProxy is free for commercial and non-commercial use, on Windows and on Linux. The source code is published under the MIT License on GitHub.

Getting started

Install sgcProxy on Windows or on Linux, then follow the Quick Start. The Configuration File topic explains how the file is checked and reloaded, and the configuration reference starts at Top Level Keys.

2Installation

Installation on Windows

The Windows installer, sgcProxy_Setup.exe, installs sgcProxy as the Windows service sgcProxy (display name "sgcProxy Reverse Proxy") and starts it. Setup needs administrator rights and 64 bit Windows 10, Windows Server 2016 or later.

What Setup does

  1. Copies sgcproxy.exe, the configuration reference (docs\configuration.md) and reference copies of the sample configuration (samples\sgcproxy.example.json, samples\conf.d\*.json) to C:\Program Files\eSeGeCe\sgcProxy.
  2. Creates the data folder C:\ProgramData\eSeGeCe\sgcProxy, or the folder given with /DATADIR=. A new data folder is restricted to SYSTEM (the service runs as LocalSystem) and the Administrators group.
  3. Registers the service with sgcproxy.exe --install --config "<data folder>\sgcproxy.json" and starts it, unless /NOSTART is given.
  4. Optional task "Allow sgcproxy.exe through Windows Firewall" (not ticked by default): adds the inbound rules "sgcProxy Reverse Proxy" for TCP and UDP (HTTP/3). The rules are bound to sgcproxy.exe, not to a list of ports, so they follow the listen ports of the configuration.
  5. Adds Start menu shortcuts to the configuration reference and to the installer notes.
The data folder
PathContent
sgcproxy.jsonThe configuration. Setup writes the starter configuration on a first install only.
conf.d\Files included by "include": ["conf.d/*.json"].
logs\error.log, access.log, sgcproxy.pid, bans.dat.
cache\Proxy cache zones.
temp\Buffered request bodies.
certs\ACME account and certificates.

Relative paths in the configuration resolve against the folder of sgcproxy.json, so every path of the starter configuration lands in the data folder. After the install, http://127.0.0.1:8080/ shows the starter page. If port 8080 is taken, change port and restart the service. See the Quick Start.

Register the service by hand

Setup registers the service for you. To register it yourself, run this from an elevated command prompt:

cd "C:\Program Files\eSeGeCe\sgcProxy"
sgcproxy.exe --install --config "C:\ProgramData\eSeGeCe\sgcProxy\sgcproxy.json"
net start sgcProxy

--install writes the --config file into the command line of the service (the ImagePath) and prints it. Without --config, the default file is written there: sgcproxy.json in the folder of sgcproxy.exe. When the command does not run as administrator it prints The service could not be registered: run the command as administrator.

sgcproxy.exe --uninstall removes the service and prints Service sgcProxy uninstalled. Stop the service first with net stop sgcProxy.

Recovery

--install also sets the recovery actions of the service and prints Recovery: restart after 5 s, 10 s and 30 s, reset after 1 day. After a crash the service manager restarts sgcProxy after 5 seconds, after a second failure after 10 seconds and after further failures after 30 seconds. The failure count resets after one day. sc qfailure sgcProxy shows these settings.

Start, stop and reload

net start sgcProxy
net stop sgcProxy
sgcproxy.exe --test --config "C:\ProgramData\eSeGeCe\sgcProxy\sgcproxy.json"
sgcproxy.exe --reload

net stop is a graceful stop: the listeners refuse new connections and the requests in flight get global.drain_timeout to finish, see global. The stop then ends with exit code 0.

--reload asks the running service to load its configuration again, without a restart, and prints Reload requested from service sgcProxy. A reload also reopens the log files, so rename a log first to rotate it. When the new configuration is invalid, the error goes to the error log and the running configuration stays. Run --test first to see the error at once.

Windows event log

The warn and error lines of logs\error.log, and a failed start, also go to the Windows Application event log. See Logging.

Run in a console

sgcproxy.exe --console --config <file> runs the proxy in the foreground of a console window, which is handy to try a configuration. Ctrl+C or Ctrl+Break stops it. Stop the service first when both would use the same ports.

Upgrade

Running a newer Setup stops the service, replaces the program files and starts the service again if it was running before. sgcproxy.json, conf.d, the logs, the cache and the certificates are never overwritten. Only the reference copies in samples\ are refreshed. The data folder of the installed copy is kept, /DATADIR is ignored on an upgrade, and the service registration is kept as it is.

Uninstall

Uninstalling stops the service, removes it with sgcproxy.exe --uninstall, removes the firewall rules and the program files, and asks "Remove the configuration and the logs?".

  • No (the default) keeps the data folder, so a later install picks it up again. The data folder is remembered in HKLM\Software\eSeGeCe\sgcProxy, value DataDir.
  • Yes also deletes the data folder.

Silent install

sgcProxy_Setup.exe /VERYSILENT /SUPPRESSMSGBOXES [/NOSTART] [/DATADIR=<folder>] [/DIR=<folder>] [/MERGETASKS=firewall] [/LOG=<file>]
SwitchMeaning
/NOSTARTRegister the service but do not start it (first install and upgrade).
/DATADIR=Data folder, default C:\ProgramData\eSeGeCe\sgcProxy. First install only.
/DIR=Program folder, default C:\Program Files\eSeGeCe\sgcProxy.
/MERGETASKS=firewallAdd the firewall rules. An upgrade keeps the choice of the previous install unless /TASKS= is given.
/LOG=Setup log file. Every command Setup runs is listed there.
sgcProxy_Setup.exe /VERYSILENT /SUPPRESSMSGBOXES /NOSTART
sgcProxy_Setup.exe /VERYSILENT /SUPPRESSMSGBOXES /DATADIR="D:\sgcProxy" /MERGETASKS=firewall /LOG="C:\Temp\sgcproxy_setup.log"

Installation on Linux

sgcProxy for Linux ships as the package sgcproxy-<version>-linux64.tar.gz, with a .sha256 checksum file next to it. It needs a 64 bit Linux distribution with systemd. The installer runs as root.

Package contents

The package has one top folder, sgcproxy-<version>-linux64/:

PathContent
bin/sgcproxyThe executable.
conf/sgcproxy.jsonThe starter configuration (one listener on port 8080), installed as the live configuration.
conf/sgcproxy.example.jsonThe full sample configuration, a reference copy. Its error log goes to the journal ("-") and the paths the proxy writes to are under /var.
conf/conf.d/*.jsonThe sample include files.
systemd/sgcproxy.serviceThe systemd unit.
install.sh, uninstall.shThe installer and the uninstaller.
READMEInstall notes.
docs/configuration.mdThe configuration reference.

The MIME types are built into the executable, so the package has no mime.types file.

Install

tar xzf sgcproxy-<version>-linux64.tar.gz
cd sgcproxy-<version>-linux64
sudo ./install.sh
OptionMeaning
--no-startInstall only, do not enable or start the service.
--config <file>Install <file> as /etc/sgcproxy/sgcproxy.json instead of the starter configuration. Only when no sgcproxy.json exists yet.

install.sh can run again at any time: it is also the upgrade. It creates the system user and group sgcproxy (no login shell, home /var/lib/sgcproxy) and installs these files:

PathContentOwner and mode
/opt/sgcproxy/sgcproxyThe executable.root:root 0755
/opt/sgcproxy/samplesReference copies of the full sample, refreshed by every run.root:root
/etc/sgcproxy/sgcproxy.json, conf.d/The configuration.root:sgcproxy 0640 and 0750
/var/lib/sgcproxyState: certs and temp.sgcproxy 0750, certs 0700
/var/cache/sgcproxyThe response cache.sgcproxy 0750
/var/log/sgcproxyThe logs.sgcproxy 0750
/etc/systemd/system/sgcproxy.serviceThe systemd unit.root:root 0644

Then it checks the configuration with sgcproxy --test as the sgcproxy user, and enables and starts the service. When the test fails, the service is not started and the installer prints config test failed. A first install starts the starter configuration on port 8080, so curl http://127.0.0.1:8080/ answers "sgcProxy is running".

The systemd unit

sgcproxy.service runs /opt/sgcproxy/sgcproxy --config /etc/sgcproxy/sgcproxy.json in the foreground as the user sgcproxy. The main settings:

SettingEffect
Type=notifyThe proxy tells systemd when it is ready, when it reloads and when it stops. No double fork, no PID file needed.
ExecReload=/bin/kill -HUP $MAINPIDsystemctl reload sgcproxy sends SIGHUP, which reloads the configuration.
Restart=on-failure, RestartSec=2systemd restarts the proxy 2 seconds after a failure.
StandardOutput=journalEvery log line written to standard output goes to the journal.
TimeoutStopSec=30Time for the connections in flight to finish on a graceful stop.
LimitNOFILE=65536A proxy holds a socket per client and one per upstream connection.
ProtectSystem=strict, ReadWritePaths=The proxy can write only to /var/log/sgcproxy, /var/lib/sgcproxy and /var/cache/sgcproxy.
AmbientCapabilities=CAP_NET_BIND_SERVICEPorts 80 and 443 without running as root.

Because of ProtectSystem=strict, every path the proxy writes to (logs, temp_path, cache zones, ACME storage, bans_file, pid_file) must be under one of the three ReadWritePaths folders. Add a folder to ReadWritePaths with systemctl edit sgcproxy if you need another one.

Manage the service

sudo systemctl status sgcproxy
sudo systemctl restart sgcproxy
sudo systemctl reload sgcproxy
sudo systemctl stop sgcproxy
sudo systemctl kill -s USR1 sgcproxy
journalctl -u sgcproxy -f

reload sends SIGHUP: the configuration is loaded again without a restart, and an invalid file leaves the running configuration in place. stop sends SIGTERM, a graceful stop. kill -s USR1 makes the proxy reopen its log files, for logrotate. Check a changed configuration before the reload:

sudo -u sgcproxy /opt/sgcproxy/sgcproxy --test --config /etc/sgcproxy/sgcproxy.json
sudo systemctl reload sgcproxy

On Linux the switches --install, --uninstall and --reload are not used. The executable prints use systemctl (see sgcproxy.service) and exits with code 1.

Logs and journald

The starter configuration writes the error log to standard output ("path": "-"), so it lands in the journal, and the access log to /var/log/sgcproxy/access.log. To rotate the access log with logrotate, send USR1 after the rotation:

/var/log/sgcproxy/*.log {
    daily
    rotate 14
    compress
    missingok
    notifempty
    postrotate
        systemctl kill -s USR1 sgcproxy
    endscript
}

Upgrade

Unpack the new package and run its install.sh. The binary is replaced and a running service is restarted to load it. An existing sgcproxy.json is never overwritten: the new starter configuration is written next to it as sgcproxy.json.new.

Uninstall

sudo /opt/sgcproxy/uninstall.sh
sudo /opt/sgcproxy/uninstall.sh --purge

Without --purge the uninstaller stops and disables the service and removes the unit and /opt/sgcproxy. The configuration, the state (certificates), the cache, the logs and the user are kept, so a later install.sh picks them up again. --purge also removes /etc/sgcproxy, /var/lib/sgcproxy, /var/cache/sgcproxy, /var/log/sgcproxy and the sgcproxy user and group.

3Quick Start

This page starts from the configuration that the installer writes and turns it into a working reverse proxy in three steps.

1. The starter configuration

On Windows the installer writes this file to C:\ProgramData\eSeGeCe\sgcProxy\sgcproxy.json:

{
  "global": {
    "error_log": { "path": "logs/error.log", "level": "warn" },
    "access_log": { "path": "logs/access.log", "format": "combined" },
    "pid_file": "logs/sgcproxy.pid",
    "temp_path": "temp",
    "server_tokens": false
  },
  "servers": [
    {
      "listen": [ { "port": 8080, "default_server": true } ],
      "server_name": ["_"],
      "locations": [
        { "match": "/", "return": { "status": 200, "body": "sgcProxy is running. Edit sgcproxy.json to add your sites.\n" } }
      ]
    }
  ]
}

It has one plain HTTP listener on port 8080 with one location / that answers every request with status 200. Open http://127.0.0.1:8080/ to see the page. The Linux starter in /etc/sgcproxy/sgcproxy.json is the same, except that the error log goes to the journal ("-") and the other paths are under /var/lib/sgcproxy and /var/log/sgcproxy.

2. Proxy an application

Replace the return action of the location with proxy_pass. JSON has no comments, so remove what you do not need:

{
  "global": {
    "error_log": { "path": "logs/error.log", "level": "warn" },
    "access_log": { "path": "logs/access.log", "format": "combined" }
  },
  "servers": [
    {
      "listen": [ { "port": 8080, "default_server": true } ],
      "server_name": ["_"],
      "locations": [
        { "match": "/", "proxy_pass": "http://127.0.0.1:3000" }
      ]
    }
  ]
}

Every request on port 8080 now goes to the application on http://127.0.0.1:3000. Check the file, then reload the running proxy:

sgcproxy.exe --test --config "C:\ProgramData\eSeGeCe\sgcProxy\sgcproxy.json"
sgcproxy.exe --reload

A valid file prints two lines:

sgcproxy: the configuration file C:\ProgramData\eSeGeCe\sgcProxy\sgcproxy.json syntax is ok
sgcproxy: configuration file C:\ProgramData\eSeGeCe\sgcProxy\sgcproxy.json test is successful

On Linux, run the test as the service user and reload with systemd:

sudo -u sgcproxy /opt/sgcproxy/sgcproxy --test --config /etc/sgcproxy/sgcproxy.json
sudo systemctl reload sgcproxy

3. HTTPS and two backend servers

This configuration redirects plain HTTP to HTTPS and balances the requests over two servers of the upstream app. The certificate and the key are PEM files, relative to the folder of the configuration file:

{
  "upstreams": {
    "app": {
      "servers": [
        { "url": "http://127.0.0.1:3000" },
        { "url": "http://127.0.0.1:3001" }
      ]
    }
  },
  "servers": [
    {
      "listen": [ { "port": 80 } ],
      "server_name": ["example.com"],
      "locations": [
        { "match": "/", "return": { "status": 301, "url": "https://$host$request_uri" } }
      ]
    },
    {
      "listen": [ { "port": 443, "tls": true, "http2": true } ],
      "server_name": ["example.com"],
      "tls": { "certificate": "certs/example.com.crt", "key": "certs/example.com.key" },
      "locations": [
        { "match": "/", "proxy_pass": "app" }
      ]
    }
  ]
}

To let sgcProxy get the certificate by itself, replace the tls object of the server with { "acme": true } and add an acme section, see ACME Certificates.

Next steps

4Running sgcProxy

Command Line

sgcproxy accepts these switches. A switch can be written as -x, --x or /x, and the name is not case sensitive.

SwitchPlatformMeaning
(none), --consoleWindows, LinuxRun the proxy. On Windows the process runs as the service when the service manager starts it, and in the console otherwise; --console forces the console. On Linux it always runs in the foreground, which is what systemd expects.
--config <file>Windows, LinuxThe configuration file. A relative name is expanded against the current folder.
--testWindows, LinuxValidate the configuration file and the certificate files, then exit. Exit code 0 when the file is valid, 1 when it is not.
--versionWindows, LinuxPrint the version, for example sgcProxy 2026.12.0.
--help, -h, -?Windows, LinuxPrint the usage text and the default configuration file.
--install [--config <file>]WindowsRegister the Windows service sgcProxy with the configuration file in its command line and set its recovery actions. Needs administrator rights.
--uninstallWindowsRemove the Windows service. Needs administrator rights.
--reloadWindowsAsk the running service to reload its configuration and reopen its log files.

Default configuration file

PlatformDefault
Windowssgcproxy.json in the folder of sgcproxy.exe. The installed service has the data folder file in its command line instead.
Linux/etc/sgcproxy/sgcproxy.json

sgcproxy --help prints the default for the current installation on its last line.

Exit codes and messages

  • --test exits with 0 and prints syntax is ok and test is successful, or exits with 1 and prints sgcproxy: [emerg] <message> and test failed. See Configuration File.
  • An unknown switch prints unknown argument: <switch> and the usage text, and exits with 1. There is no short form -c: use --config.
  • --config as the last argument prints --config needs a file name.
  • On Linux, --install, --uninstall and --reload print use systemctl (see sgcproxy.service) and exit with 1.
  • A graceful stop ends with exit code 0.

Signals and service controls

ActionWindowsLinux
Reload the configurationsgcproxy.exe --reload (the service control PARAMCHANGE)SIGHUP, systemctl reload sgcproxy
Reopen the log filessgcproxy.exe --reloadSIGUSR1, systemctl kill -s USR1 sgcproxy
Graceful stopnet stop sgcProxy, Ctrl+C in the consoleSIGTERM, systemctl stop sgcproxy

Examples

sgcproxy --version
sgcproxy --test --config conf\sgcproxy.json
sgcproxy --console --config conf\sgcproxy.json
sgcproxy --install --config "C:\ProgramData\eSeGeCe\sgcProxy\sgcproxy.json"
sgcproxy --reload
sgcproxy --uninstall

Configuration File

sgcProxy reads one JSON file, plus the files it includes. The file is UTF-8, with or without a BOM. JSON has no comments.

Structure

The file is one JSON object. Every section is optional:

SectionContent
includeExtra files with more servers and upstreams.
globalLogs, timeouts, request limits, graceful drain, the event driven forward and the admin listener.
tlsDefaults of every TLS listener.
acmeAutomatic certificates.
firewallAddress lists, WAF, flood protection, GeoIP.
limitsNamed rate limit zones.
cachesNamed cache zones.
upstreamsNamed groups of backend servers.
serversVirtual servers with their listen entries and locations.

Sizes, durations, booleans and addresses accept several spellings, see Value Types. Relative paths resolve against the folder of the main configuration file, not against the current folder.

Strict validation

An unknown key, a wrong type, a value out of range or a duplicate key is an error. Every error names the key by its JSON path and the file, for example:

sgcproxy: [emerg] unknown key "proxy_pas" at servers[0].locations[0].proxy_pas in C:\ProgramData\eSeGeCe\sgcProxy\sgcproxy.json

Certificate, key and CA files must exist, both in --test and when the configuration loads. A start with an invalid file fails, and the error goes to the error log (and, on Windows, to the event log).

Test a configuration

--test validates the file like nginx -t. It checks the JSON, every key, the references between sections and the certificate files of the TLS listeners:

sgcproxy --test --config "C:\ProgramData\eSeGeCe\sgcProxy\sgcproxy.json"

A valid file prints two lines and exits with code 0:

sgcproxy: the configuration file C:\ProgramData\eSeGeCe\sgcProxy\sgcproxy.json syntax is ok
sgcproxy: configuration file C:\ProgramData\eSeGeCe\sgcProxy\sgcproxy.json test is successful

An invalid file prints the first error and exits with code 1:

sgcproxy: [emerg] upstream "backend" is not defined at servers[0].locations[0].proxy_pass in C:\ProgramData\eSeGeCe\sgcProxy\sgcproxy.json
sgcproxy: configuration file C:\ProgramData\eSeGeCe\sgcProxy\sgcproxy.json test failed

Warnings are printed as sgcproxy: [warn] <message> before the two success lines. Troubleshooting lists the messages of common mistakes.

Include files

include lists extra files, relative to the main file. Wildcards (*, ?) are allowed in the file name only, and the matches are read in name order. A missing file without a wildcard is an error, a wildcard with no match is not. Included files may contain only servers and upstreams. The main file:

{
  "include": ["configfile_conf.d/*.json"],
  "global": {
    "error_log": { "path": "logs/error.log", "level": "warn" }
  },
  "servers": [
    {
      "listen": [ { "port": 8080, "default_server": true } ],
      "locations": [
        { "match": "/", "return": { "status": 404, "body": "unknown site\n" } }
      ]
    }
  ]
}

The included file configfile_conf.d/shop.json adds a site and its upstream:

{
  "upstreams": {
    "shop": { "servers": [ { "url": "http://127.0.0.1:5000" } ] }
  },
  "servers": [
    {
      "listen": [ { "port": 8080 } ],
      "server_name": ["shop.example.com"],
      "locations": [
        { "match": "/", "proxy_pass": "shop" }
      ]
    }
  ]
}

A file included twice, or an upstream defined in two files, is an error that names both files.

Hot reload

A reload builds a new configuration from the files and swaps it in only when it is valid. Otherwise the error is logged and the running configuration stays. Trigger it with:

  • Windows: sgcproxy.exe --reload.
  • Linux: systemctl reload sgcproxy, which sends SIGHUP.

A reload keeps every listener whose address and port did not change. New requests take the new configuration, and the requests in flight finish on the old one. Open WebSocket tunnels keep their configuration. A listener that the new configuration removes is drained and closed, and a new one starts. Certificates are swapped for new connections, and open connections keep theirs. Upstream health starts fresh, and limit zones start new counters. /status counts the reloads that succeeded and failed and shows the last error, see Status Page and Prometheus Metrics.

Graceful drain

Graceful drain. On a stop (SIGTERM, the service stop, Ctrl+C), and for the listeners a reload removes, the listener refuses new TCP connections, every response from then on carries Connection: close, and the requests in flight get drain_timeout to finish (on a stop the WebSocket and CONNECT tunnels too). At the deadline the requests still waiting on their upstream are cut within 1 s, the tunnels are closed and the listener closes; the stop then exits with code 0.

HTTP/2 and HTTP/3 connections get no GOAWAY frame yet (the library has no server side GOAWAY call), they are closed with the listener. A reload (SIGHUP, SERVICE_CONTROL_PARAMCHANGE, sgcproxy --reload) keeps every listener whose address and port did not change, new requests take the new snapshot and the requests in flight finish on the old one.

5Configuration Reference

Value Types

Many keys take a size, a duration, a boolean, an address or a name. The reference tables use these types, often with a range such as duration 1ms..1h.

TypeSyntaxnginx
sizeJSON number (bytes) or string "512", "64k", "10m", "1g" (case-insensitive, 1k = 1024)client_max_body_size 10m
durationJSON number (seconds) or string "250ms", "30s", "5m", "1h", "1d". No compound valueskeepalive_timeout 75s
booleantrue / false, or the strings "on", "off", "yes", "no", "true", "false"on / off
addressIPv4 or IPv6, optionally CIDR: "10.0.0.0/8", "2001:db8::/32"allow 10.0.0.0/8
namezone and upstream names: letters, digits, _, -

Durations have no compound values: write "90m", not "1h30m". The example uses several spellings:

{
  "global": {
    "client_max_body_size": "10m",
    "large_header_size": 16384,
    "client_header_timeout": 30,
    "keepalive_timeout": "75s",
    "drain_timeout": "250ms",
    "server_tokens": "off"
  },
  "servers": [
    {
      "listen": [ { "port": 8080 } ],
      "allow": ["10.0.0.0/8", "2001:db8::/32"],
      "locations": [
        { "match": "/", "return": { "status": 200, "body": "ok" } }
      ]
    }
  ]
}

Top Level Keys

The configuration file is one JSON object with these keys. An empty section takes the defaults.

KeyTypeDefaultDescription
includestring[][]Extra files, relative to the main file. See the note below the table.
globalobjectProcess and client connection settings
tlsobjectDefaults of every TLS listener
acmeobjectabsentAutomatic certificates. Required by tls.acme: true
firewallobjectabsentAbsent = no firewall
limitsobject{}Named rate-limit zones
cachesobject{}Named cache zones
upstreamsobject{}Named backend groups
serversarray[]Virtual servers
include

Extra files, relative to the main file. Wildcards (*, ?) only in the file name, matches are read in name order. A missing file without wildcard is an error, a wildcard with no match is not.

Included files may contain only servers and upstreams. A file included twice, or an upstream defined in two files, is an error that names both files. nginx include conf.d/*.conf.

The firewall section turns the firewall on as soon as it is present, even when it is empty. Leave it out when you do not want a firewall. The same holds for acme.

{
  "include": [],
  "global": {},
  "tls": {},
  "limits": {},
  "caches": {},
  "upstreams": {},
  "servers": [
    {
      "listen": [ { "port": 8080 } ],
      "locations": [
        { "match": "/", "return": { "status": 200, "body": "ok" } }
      ]
    }
  ]
}

See also Configuration File.

global

global holds the logs, the client connection limits and the process settings. The keys of global.admin are on the page global.admin.

KeyTypeDefaultDescriptionnginx
error_log.pathstring"logs/error.log""-" = stdouterror_log
error_log.levelenumwarndebug, info, notice, warn, errorerror_log ... warn
access_log.pathstring"logs/access.log""-" = stdout, "off" = noneaccess_log
access_log.formatenumcombinedcombined, jsonlog_format
pid_filestringnonePID filepid
worker_threadsinteger 0..102400 = autoworker_processes
server_tokensbooleanfalseSend the version in Serverserver_tokens
temp_pathstring"temp"Request body buffersclient_body_temp_path
client_header_timeoutduration 1ms..1h60sclient_header_timeout
client_body_timeoutduration 1ms..1h60sclient_body_timeout
keepalive_timeoutduration 0..1h75s0 disables keep-alivekeepalive_timeout
keepalive_requestsinteger 1..100000001000keepalive_requests
client_max_body_sizesize 0..1024g1m0 = unlimited. See the note below the table.client_max_body_size
large_header_sizesize 1k..1m8kLargest request headerlarge_client_header_buffers
max_headersinteger 1..10000100Header count limit
drain_timeoutduration 0..1h30sGraceful stop: how long the requests in flight (and on a stop the tunnels) may take before they are cutworker_shutdown_timeout
proxy_asyncbooleanfalseSet it to true to turn on the event driven forward (see below): a proxied HTTP/1.1 request then takes it when it qualifies. With false every request goes through the blocking forward. See the note below the table.
client_max_body_size

0 = unlimited. Checked early on h1, h2 and h3: a Content-Length above it gets 413 before any body byte is read, a body without one gets 413 as soon as it passes the limit, and on h2 and h3 the rest of the body is refused (RST_STREAM(NO_ERROR), STOP_SENDING) while the connection stays usable. h2 and h3 request bodies stream to the upstream under flow control (chunked when the client sends no length), so an upload holds no more than the stream window; HTTP/3 streaming needs the native TLS engine. The HTTP/2 and HTTP/3 servers also get the largest limit of the configuration as their own; a reload that changes it reaches HTTP/3 after a restart (a warning is logged).

proxy_async

The default is false. Set it to true to turn on the event driven forward (see below): a proxied HTTP/1.1 request then takes it when it qualifies. With false every request goes through the blocking forward. Read per request from the snapshot, so a reload switches it for the next requests.

Example

{
  "global": {
    "error_log": { "path": "logs/error.log", "level": "warn" },
    "access_log": { "path": "logs/access.log", "format": "combined" },
    "pid_file": "logs/sgcproxy.pid",
    "worker_threads": 0,
    "server_tokens": false,
    "temp_path": "temp",
    "client_header_timeout": "60s",
    "client_body_timeout": "60s",
    "keepalive_timeout": "75s",
    "keepalive_requests": 1000,
    "client_max_body_size": "1m",
    "large_header_size": "8k",
    "max_headers": 100,
    "drain_timeout": "30s",
    "proxy_async": true,
    "admin": { "enabled": true, "listen": "127.0.0.1:8099", "allow": ["127.0.0.1", "::1"] }
  },
  "servers": [ { "listen": [ { "port": 8080 } ], "locations": [ { "match": "/", "return": { "status": 200, "body": "ok" } } ] } ]
}

Graceful drain

Graceful drain. On a stop (SIGTERM, the service stop, Ctrl+C), and for the listeners a reload removes, the listener refuses new TCP connections, every response from then on carries Connection: close, and the requests in flight get drain_timeout to finish (on a stop the WebSocket and CONNECT tunnels too). At the deadline the requests still waiting on their upstream are cut within 1 s, the tunnels are closed and the listener closes; the stop then exits with code 0.

HTTP/2 and HTTP/3 connections get no GOAWAY frame yet (the library has no server side GOAWAY call), they are closed with the listener. A reload (SIGHUP, SERVICE_CONTROL_PARAMCHANGE, sgcproxy --reload) keeps every listener whose address and port did not change, new requests take the new snapshot and the requests in flight finish on the old one.

Event driven forward

proxy_async turns the event driven forward of proxied HTTP/1.1 requests on and off; it is off by default. See Event Driven Forward.

global.admin

global.admin opens a small admin listener on a loopback address. Without the object there is no admin listener.

KeyTypeDefaultDescriptionnginx
adminobjectabsentAbsent = no admin listener
admin.enabledbooleantruefalse keeps the block but opens no admin listener
admin.listenstring"127.0.0.1:8099"<ipv4>:<port> or [<ipv6>]:<port>, a loopback address only (127.x.x.x or ::1)
admin.allowaddress[]["127.0.0.1", "::1"]Clients allowed on the admin listener

Endpoints

RequestAnswer
GET /statusThe state of the proxy as JSON.
GET /metricsCounters and gauges in the Prometheus text format 0.0.4.
POST /cache/purgeRemoves entries from the proxy cache, see Proxy Cache.

Only a loopback address is accepted in listen (127.x.x.x or ::1), any other address is a configuration error at global.admin.listen. 127.0.0.1 also binds [::1] on the same port when the host has IPv6. A client outside allow gets 403. A port that cannot be bound is logged at error level and the proxy runs without the admin listener.

{
  "global": {
    "admin": { "listen": "127.0.0.1:8099", "allow": ["127.0.0.1", "::1"] }
  },
  "servers": [
    {
      "listen": [ { "port": 8080 } ],
      "locations": [
        { "match": "/", "proxy_pass": "http://127.0.0.1:8081" }
      ]
    }
  ]
}

The fields of /status and the metric names are described in Status Page and Prometheus Metrics.

tls

tls holds the defaults of every TLS listener. The certificate of each server is set in the tls object of the server, see servers.

KeyTypeDefaultDescriptionnginx
engineenumnativenative (the sgcWebSockets native TLS engine), openssl
versionsstring[]["1.3", "1.2"]1.3, 1.2, at least one, no duplicatesssl_protocols
groupsstring[]["X25519MLKEM768", "X25519", "secp256r1", "secp384r1"]Key exchange groups, in orderssl_ecdh_curve
ciphersstring[]engine defaultCipher suitesssl_ciphers
session_ticketsbooleantruessl_session_tickets
hstsobjectabsentDefault HSTS of every TLS serveradd_header Strict-Transport-Security
hsts.max_ageduration 0..3650drequiredSent in secondsmax-age=
hsts.include_subdomainsbooleanfalseincludeSubDomains
hsts.preloadbooleanfalsepreload
openssl.lib_pathstringrequired in opensslFolder of the OpenSSL libraries

Example

{
  "tls": {
    "engine": "native",
    "versions": ["1.3", "1.2"],
    "groups": ["X25519MLKEM768", "X25519", "secp256r1", "secp384r1"],
    "session_tickets": true,
    "hsts": { "max_age": "365d", "include_subdomains": false, "preload": false }
  },
  "servers": [
    {
      "listen": [ { "port": 443, "tls": true, "default_server": true } ],
      "server_name": ["example.com", "www.example.com"],
      "tls": { "certificate": "certs/example.com.crt", "key": "certs/example.com.key" },
      "locations": [
        { "match": "/", "proxy_pass": "http://127.0.0.1:8081" }
      ]
    }
  ]
}

With the openssl engine, openssl.lib_path names the folder of the OpenSSL libraries. HTTP/3 and the TLS-ALPN-01 challenge need the native engine.

{
  "tls": {
    "engine": "openssl",
    "openssl": { "lib_path": "openssl" }
  },
  "servers": [
    {
      "listen": [ { "port": 443, "tls": true, "default_server": true } ],
      "server_name": ["example.com", "www.example.com"],
      "tls": { "certificate": "certs/example.com.crt", "key": "certs/example.com.key" },
      "locations": [
        { "match": "/", "proxy_pass": "http://127.0.0.1:8081" }
      ]
    }
  ]
}

ciphers takes the cipher suite names of the engine. Leave it out to use the defaults of the engine. See TLS and Post-Quantum Key Exchange.

acme

acme turns on automatic certificates. A server gets a certificate from this section when its tls object is { "acme": true }.

KeyTypeDefaultDescription
directoryURLrequiredACME directory, for example https://acme-v02.api.letsencrypt.org/directory
emailstringnoneAccount contact
storagestring"certs"Folder of the account key and certificates
renew_beforeduration 1h..180d30dRenew when the certificate expires within this time
check_intervalduration 1m..7d12hHow often the certificate manager checks every certificate for renewal
challengeenumhttp-01http-01 (port 80) or tls-alpn-01 (port 443, native TLS only), see below
eab.kid, eab.hmac_keystringboth required in eabExternal account binding

Example

{
  "acme": {
    "directory": "https://acme-v02.api.letsencrypt.org/directory",
    "email": "admin@example.com",
    "storage": "certs",
    "renew_before": "30d",
    "check_interval": "12h",
    "challenge": "http-01"
  },
  "servers": [
    {
      "listen": [ { "port": 80 } ],
      "server_name": ["example.com", "www.example.com"],
      "locations": [
        { "match": "/", "return": { "status": 301, "url": "https://$host$request_uri" } }
      ]
    },
    {
      "listen": [ { "port": 443, "tls": true, "http2": true } ],
      "server_name": ["example.com", "www.example.com"],
      "tls": { "acme": true },
      "locations": [
        { "match": "/", "proxy_pass": "http://127.0.0.1:8081" }
      ]
    }
  ]
}

A CA that needs external account binding gives you a key id and an HMAC key for eab:

{
  "acme": {
    "directory": "https://acme.example.net/directory",
    "email": "admin@example.com",
    "challenge": "tls-alpn-01",
    "eab": { "kid": "kid-1", "hmac_key": "c2VjcmV0LWtleS1mcm9tLXRoZS1jYQ" }
  },
  "servers": [
    {
      "listen": [ { "port": 443, "tls": true } ],
      "server_name": ["example.com"],
      "tls": { "acme": true },
      "locations": [
        { "match": "/", "proxy_pass": "http://127.0.0.1:8081" }
      ]
    }
  ]
}

How issuance, renewal and the two challenges work is described in ACME Certificates.

firewall

The firewall section turns the firewall on. Without the section there is no firewall.

KeyTypeDefaultDescription
allowaddress[][]Only these clients (when not empty)
denyaddress[][]Blocked clients
trusted_proxiesaddress[][]Proxies whose forwarded header is believed
forwarded_modeenumx-forwarded-forx-forwarded-for, x-real-ip, both
trusted_hopsinteger 1..161
waf.sql_injectionbooleanfalse
waf.xssbooleanfalse
waf.path_traversalbooleanfalse
waf.command_injectionbooleanfalse
waf_headersstring[]["User-Agent", "Referer", "Cookie"]Header names (RFC 9110 tokens) whose values the WAF inspects; [] = the request target only
brute_forceobjectabsent = off
brute_force.max_attemptsinteger 1..1000005
brute_force.windowduration 1s..1d60s
brute_force.ban_timeduration 1s..365d5m
floodobjectabsent = off
flood.max_requests_per_secondinteger 1..1000000100Per client
bot_detectionbooleanfalse
geoipobjectabsent = off
geoip.databasestringrequired in geoipCountry database
geoip.allow_countriesstring[][]ISO 3166-1 alpha-2 codes
geoip.deny_countriesstring[][]Cannot be combined with allow_countries
bans_filestringnoneBans kept across restarts

Examples

{
  "firewall": {
    "allow": [],
    "deny": ["203.0.113.0/24", "2001:db8:bad::/48"],
    "trusted_proxies": ["10.0.0.0/8"],
    "forwarded_mode": "x-forwarded-for",
    "trusted_hops": 1,
    "waf": { "sql_injection": true, "xss": true, "path_traversal": true, "command_injection": true },
    "waf_headers": ["User-Agent", "Referer", "Cookie"],
    "flood": { "max_requests_per_second": 100 },
    "bot_detection": false,
    "bans_file": "logs/bans.dat"
  },
  "limits": {
    "api": { "strategy": "token_bucket", "rate": 10, "per": "second", "burst": 20, "key": "ip", "status": 429, "retry_after": true }
  },
  "servers": [
    {
      "listen": [ { "port": 8080 } ],
      "locations": [
        { "match": "/api/", "proxy_pass": "http://127.0.0.1:8081", "limit": "api" },
        { "match": "/", "proxy_pass": "http://127.0.0.1:8081" }
      ]
    }
  ]
}

Brute force protection and GeoIP have their own objects. geoip.database names the country database file:

{
  "firewall": {
    "brute_force": { "max_attempts": 5, "window": "60s", "ban_time": "5m" },
    "geoip": { "database": "geoip/countries.dat", "allow_countries": ["ES", "FR", "DE"] }
  },
  "servers": [ { "listen": [ { "port": 8080 } ], "locations": [ { "match": "/", "return": { "status": 200, "body": "ok" } } ] } ]
}

brute_force needs failed attempts, which sgcProxy does not report yet, so it has no effect today. See Firewall and Rate Limiting.

limits

limits defines named rate limit zones: "limits": { "<name>": { ... } }. A location uses a zone with its limit key. This is nginx limit_req_zone and limit_req.

KeyTypeDefaultDescription
strategyenumtoken_buckettoken_bucket, sliding_window, fixed_window
rateinteger 1..1000000requiredRequests per per
perenumsecondsecond, minute, hour
burstinteger 0..10000000Extra tokens, token_bucket only (capacity = rate + burst)
keystringipip, api_key, header:<Name>
statusinteger 400..599429Status when throttled
retry_afterbooleantrueSend Retry-After

Example

{
  "limits": {
    "api": { "strategy": "token_bucket", "rate": 10, "per": "second", "burst": 20 },
    "partners": { "strategy": "sliding_window", "rate": 600, "per": "minute", "key": "header:X-Partner-Id", "status": 503, "retry_after": false },
    "login": { "strategy": "fixed_window", "rate": 5, "per": "minute", "key": "ip" },
    "keys": { "rate": 1000, "per": "hour", "key": "api_key" }
  },
  "servers": [
    {
      "listen": [ { "port": 8080 } ],
      "locations": [
        { "match": "= /login", "proxy_pass": "http://127.0.0.1:8081", "limit": "login" },
        { "match": "/api/", "proxy_pass": "http://127.0.0.1:8081", "limit": "api" },
        { "match": "/partners/", "proxy_pass": "http://127.0.0.1:8081", "limit": "partners" },
        { "match": "/v2/", "proxy_pass": "http://127.0.0.1:8081", "limit": "keys" }
      ]
    }
  ]
}

See Firewall and Rate Limiting.

caches

caches defines named cache zones on disk: "caches": { "<name>": { ... } }. A proxy_pass location uses a zone with its cache object. This is nginx proxy_cache_path.

KeyTypeDefaultDescription
pathstringrequiredCache folder
max_sizesize 1m..1048576g1g
inactiveduration 1s..365d1dEntries not read for this time are removed
default_ttlduration 0..365d00 = only cache what the upstream allows (Cache-Control, Expires)
keystring"$scheme$host$request_uri"proxy_cache_key
max_entriesinteger 1..10000000100000Entries above this are evicted, least recently used first (the role of nginx keys_zone)

Example

{
  "global": {
    "admin": { "listen": "127.0.0.1:8099" }
  },
  "caches": {
    "pages": { "path": "cache/pages", "max_size": "1g", "inactive": "1d", "default_ttl": 0, "key": "$scheme$host$request_uri", "max_entries": 100000 }
  },
  "servers": [
    {
      "listen": [ { "port": 8080 } ],
      "locations": [
        {
          "match": "/",
          "proxy_pass": "http://127.0.0.1:8081",
          "cache": {
            "zone": "pages",
            "methods": ["GET", "HEAD"],
            "valid": { "200 302": "10m", "404": "1m" },
            "use_stale": ["error", "timeout", "updating", "http_502", "http_503"],
            "lock_timeout": "5s",
            "bypass": ["$cookie_nocache", "$arg_nocache"],
            "no_cache": ["$http_pragma"],
            "status_header": true,
            "set_cookie": false
          }
        }
      ]
    }
  ]
}

The keys of the cache object of a location are on the page [servers[].locations](@r_loc). How the cache behaves is described in Proxy Cache.

upstreams

upstreams defines named groups of backend servers: "upstreams": { "<name>": { ... } }. A location sends requests to a group with "proxy_pass": "<name>". This is nginx upstream.

KeyTypeDefaultDescriptionnginx
balanceenumround_robinround_robin, least_conn, ip_hash, hashleast_conn, ip_hash, hash
hash_keystringrequired with hashOnly valid with hash, for example "$remote_addr"hash $key
consistentbooleanfalseOnly valid with hash: a consistent (ketama) hash, removing one of n servers moves only about 1/n of the keyshash $key consistent
keepaliveinteger 0..1000032Idle connections kept per server of the upstream, one cache shared by all worker threads (see keep-alive sizing below)keepalive
keepalive_timeoutduration 0..1d60skeepalive_timeout
keepalive_requestsinteger 1..100000001000keepalive_requests
connect_timeoutduration 1ms..1h5sproxy_connect_timeout
send_timeoutduration 1ms..1d60sAlso bounds a stalled write to the client of a WebSocket tunnelproxy_send_timeout
read_timeoutduration 1ms..1d60sproxy_read_timeout
retriesinteger 0..1001Next server attemptsproxy_next_upstream_tries
retry_onstring[]["error", "timeout"]error, timeout, 502, 503, 504proxy_next_upstream
serversobject[]requiredAt least one, at least one not backup, no duplicate urlserver
servers[].urlstringrequiredhttp(s)://host:port, no pathserver host:port
servers[].weightinteger 1..10001weight=
servers[].max_failsinteger 0..10001max_fails=
servers[].fail_timeoutduration 0..1d10sfail_timeout=
servers[].backupbooleanfalsebackup
servers[].downbooleanfalsedown
health_checkobjectabsent = offActive checkshealth_check (nginx Plus)
health_check.pathstring"/"Must start with /uri=
health_check.intervalduration 100ms..1h5sinterval=
health_check.timeoutduration 1ms..1h2s
health_check.failsinteger 1..1003fails=
health_check.passesinteger 1..1002passes=
health_check.expect_statusstring or number"200-399""200", 200 or "<from>-<to>" within 100-599match status=
tlsobjectabsentRequires every server to be https
tls.verifybooleantrueVerify the upstream certificateproxy_ssl_verify
tls.ca_filestringsystem storeMust existproxy_ssl_trusted_certificate
tls.snistringhost of the urlproxy_ssl_name
tls.client_certificate, tls.client_keystringnoneTogether, both must existproxy_ssl_certificate, proxy_ssl_certificate_key

Example

{
  "upstreams": {
    "app": {
      "balance": "least_conn",
      "keepalive": 64,
      "keepalive_timeout": "60s",
      "keepalive_requests": 1000,
      "connect_timeout": "5s",
      "send_timeout": "60s",
      "read_timeout": "60s",
      "retries": 1,
      "retry_on": ["error", "timeout", "502", "503"],
      "servers": [
        { "url": "http://10.0.0.11:8080", "weight": 2 },
        { "url": "http://10.0.0.12:8080", "max_fails": 3, "fail_timeout": "30s" },
        { "url": "http://10.0.0.13:8080", "backup": true },
        { "url": "http://10.0.0.14:8080", "down": true }
      ],
      "health_check": { "path": "/health", "interval": "5s", "timeout": "2s", "fails": 3, "passes": 2, "expect_status": "200-399" }
    },
    "secure": {
      "servers": [ { "url": "https://10.0.1.10:8443" } ],
      "tls": {
        "verify": true,
        "ca_file": "certs/ca.pem",
        "sni": "api.internal",
        "client_certificate": "certs/client.crt",
        "client_key": "certs/client.key"
      }
    }
  },
  "servers": [
    {
      "listen": [ { "port": 8080 } ],
      "locations": [
        { "match": "/secure/", "proxy_pass": "secure" },
        { "match": "/", "proxy_pass": "app" }
      ]
    }
  ]
}

The balancing methods, passive health, active health checks and keep-alive sizing are described in Load Balancing.

servers

servers is the list of virtual servers. This is nginx server. The keys of a listen entry are on the page [servers[].listen](@r_listen), the keys of a location on [servers[].locations](@r_loc).

KeyTypeDefaultDescriptionnginx
server_namestring[][]"example.com", "*.example.com", ".example.com" (the name and its subdomains), "~regex" (case-insensitive). Empty = any name. The same (address, port, server_name) in two servers is an errorserver_name
tlsobjectrequired when a listen has tls
tls.certificate, tls.keystringrequiredPEM files, must existssl_certificate, ssl_certificate_key
tls.passwordstringnoneKey passwordssl_password_file
tls.acmebooleanfalseCertificate from acme, then no certificate, key, password
hstsobjecttls.hstsOverrides the global HSTS, same keys
allow, denyaddress[][]Per-server access listsallow, deny
locationsobject[][]Two locations with the same match are an errorlocation

Server selection

For each listen address and port, sgcProxy picks the server like nginx: by the Host header, or by the TLS SNI name on a TLS listener. An exact name wins, then the longest leading wildcard (*.example.com), then the first regular expression in configuration order. A request whose name matches no server goes to the default_server of that address and port.

{
  "servers": [
    {
      "listen": [ { "port": 8080, "default_server": true } ],
      "locations": [
        { "match": "/", "return": { "status": 404, "body": "unknown host\n" } }
      ]
    },
    {
      "listen": [ { "port": 8080 } ],
      "server_name": ["example.com", "www.example.com"],
      "locations": [
        { "match": "/", "proxy_pass": "http://127.0.0.1:8081" }
      ]
    },
    {
      "listen": [ { "port": 8080 } ],
      "server_name": ["*.example.org", ".example.net", "~^api[0-9]+\\.example\\.com$"],
      "deny": ["192.0.2.0/24"],
      "locations": [
        { "match": "/", "proxy_pass": "http://127.0.0.1:8082" }
      ]
    }
  ]
}

servers[].listen

listen is the list of addresses and ports of a server. Every server needs at least one entry. All servers that listen on the same address and port share one listener, and a wildcard address covers the specific addresses of its port, like nginx.

KeyTypeDefaultDescriptionnginx
listenobject[]requiredAt least onelisten
listen[].addressstring"0.0.0.0"IPv4 or IPv6 ("::")listen addr:port
listen[].portinteger 1..65535required
listen[].tlsbooleanfalseA port is either tls or plain in every serverssl
listen[].http2booleanfalseRequires tls, h2c is not supported. See the note below the table.http2
listen[].http3booleanfalseRequires tls and the NativeTLS engine (a listener on OpenSSL keeps HTTP/3 off and logs a warning). See the note below the table.listen ... quic, add_header Alt-Svc
listen[].default_serverbooleanfalseOne per address:portdefault_server
listen[].http2

Requires tls, h2c is not supported. ALPN offers h2 next to http/1.1. Limits: 128 concurrent streams per connection (the nginx default), the library defaults for the rest (64 KB initial window, 16 KB frames, 256 KB header list); no server push.

A request with Upgrade or another connection-specific header (a WebSocket handshake over h2, RFC 8441 is not enabled) gets 400 as RFC 9113 8.2.2 requires, CONNECT gets 405.

listen[].http3

Requires tls and the NativeTLS engine (a listener on OpenSSL keeps HTTP/3 off and logs a warning). HTTP/3 on the UDP port of the same number. A QUIC handshake gets the certificate of the server its SNI name selects, as on TCP (exact, wildcard, suffix and regex names, tls.certificate or tls.acme); no SNI or an unknown name gets the certificate of the default server of the listen entry.

Requests take the same path as h1 and h2 (router, firewall rules, WAF, limits, return, static files, proxy_pass, HSTS, access log with protocol HTTP/3.0); responses are streamed with backpressure and a cancelled stream closes the upstream connection. A request with Upgrade or another connection-specific header is refused (RFC 9114 4.2), CONNECT gets 405. While the QUIC endpoint runs, the h1 and h2 responses of every server on the listener carry Alt-Svc: h3=":<port>"; ma=86400 under the add_header status rules, unless the location sets Alt-Svc in its own add_header; there is no key for it.

Limits today: an h3 request has no client address (the access log and the address rules see none), and the firewall deny list is not checked when a QUIC connection is accepted. A certificate reload (configuration reload, ACME issuance or renewal) reaches new QUIC connections for every host too, open ones keep theirs.

Example

{
  "servers": [
    {
      "listen": [
        { "address": "0.0.0.0", "port": 443, "tls": true, "http2": true, "http3": true, "default_server": true },
        { "address": "::", "port": 443, "tls": true, "http2": true }
      ],
      "server_name": ["example.com"],
      "tls": { "certificate": "certs/example.com.crt", "key": "certs/example.com.key" },
      "locations": [
        { "match": "/", "proxy_pass": "http://127.0.0.1:8081" }
      ]
    },
    {
      "listen": [ { "address": "127.0.0.1", "port": 8080 } ],
      "server_name": ["internal"],
      "locations": [
        { "match": "/", "return": { "status": 200, "body": "internal\n" } }
      ]
    }
  ]
}

See HTTP/2 and HTTP/3.

servers[].locations

locations is the list of locations of a server. This is nginx location. Each location has a match and exactly one action: proxy_pass, root, alias or return.

KeyTypeDefaultDescriptionnginx
matchstringrequired"/prefix", "= /exact", "^~ /prefix" (no regex check after a match), "~ regex", "~* regex" (case-insensitive)location
proxy_passstringAction: an upstream name or http(s)://host[:port][/path]proxy_pass
rootstringAction: files under this folder plus the URIroot
aliasstringAction: the matched prefix is replaced by this folderalias
returnobjectAction: {status 100..599, body} or {status 301/302/303/307/308, url}return
indexstring[]["index.html"]root/alias onlyindex
try_filesstring[][]root/alias only, for example ["$uri", "$uri/", "=404"]try_files
autoindexbooleanfalseroot/alias onlyautoindex
typesobject{}root/alias only: media type to extensions without dot, {"text/x-foo": ["foo", "fo"]}, merged over the built-in nginx mime.types table (nginx replaces it)types
default_typestring"application/octet-stream"root/alias only: the type of an extension that no table listsdefault_type
expiresstring or number"off"root/alias only: "off", "epoch", "max" or a duration up to 3650d, negative allowed ("-1h")expires
log_not_foundbooleantrueroot/alias only: write a missing file to the error loglog_not_found
strip_prefixbooleanfalseproxy_pass only: remove the matched prefixproxy_pass http://u/
proxy_set_headerobject{}proxy_pass only: {"Header": "value"}, "" removesproxy_set_header
proxy_hide_headerstring[][]proxy_pass onlyproxy_hide_header
add_headerobject{}Response headersadd_header
websocketbooleantrueproxy_pass only: pass WebSocket upgradesproxy_set_header Upgrade
bufferingbooleantrueproxy_pass only: buffer responsesproxy_buffering
request_bufferingbooleantrueproxy_pass only: buffer request bodiesproxy_request_buffering
limitstringnoneName of a limits zonelimit_req zone=
cacheobjectabsent = offproxy_pass onlyproxy_cache
cache.zonestringrequiredName of a caches zoneproxy_cache
cache.ttlduration 0..365dzone default_ttlproxy_cache_valid
cache.methodsstring[]["GET", "HEAD"]GET, HEAD, POSTproxy_cache_methods
cache.bypass_headerstringnoneA request with this header skips the cacheproxy_cache_bypass
cache.keystringzone keyVariables $scheme, $host, $http_host, $request_uri, $uri, $args, $request_method, $http_<name>, $cookie_<name>, $arg_<name>proxy_cache_key
cache.validobject{}Status codes (space separated, 200..599, or any) to a duration 0..365d, for responses without max-age, s-maxage or Expires, for example {"200 302": "10m", "404": "1m"}proxy_cache_valid
cache.bypassstring[][]Conditions $http_<name>, $cookie_<name>, $arg_<name>: one that is not empty and not 0 skips the lookup and the store (BYPASS)proxy_cache_bypass
cache.no_cachestring[][]The same conditions: the response is not storedproxy_no_cache
cache.use_stalestring[][]error, timeout, updating, http_500, http_502, http_503, http_504proxy_cache_use_stale
cache.lock_timeoutduration 0..1m5sHow long a request waits for the fill of the same keyproxy_cache_lock_timeout
cache.status_headerbooleantrueSends X-Cache-Statusadd_header X-Cache-Status $upstream_cache_status
cache.set_cookiebooleanfalsetrue stores responses with Set-Cookie, without their Set-Cookie fieldsproxy_ignore_headers Set-Cookie
gzip.enabledbooleanfalsegzip
gzip.typesstring[]["text/html", "text/css", "application/javascript", "application/json", "image/svg+xml"]gzip_types
gzip.min_lengthsize 0..1g1kgzip_min_length
gzip.levelinteger 1..95gzip_comp_level
gzip.proxiedstring[]["off"]For requests with Via: off, or any of expired, no-cache, no-store, private, no_last_modified, no_etag, auth, anygzip_proxied
gzip.varybooleanfalseAdd Vary: Accept-Encoding to compressible responsesgzip_vary
client_max_body_sizesize 0..1024gglobal.client_max_body_sizeOverride, checked early on h1, h2 and h3 as the global keyclient_max_body_size
read_timeoutduration 1ms..1dthe upstream read_timeout, 60s for a URLproxy_pass only, overrideproxy_read_timeout
allow, denyaddress[][]Per-location access listsallow, deny

Rules

A location has exactly one action. Two actions (for example proxy_pass and root) or none are errors, and so is an option of another action (for example strip_prefix with root). An upstream, limit zone or cache zone that is not defined in any file is an error.

Location order

The order follows nginx. An exact match (=) wins at once. Otherwise the longest prefix is found. When that prefix is ^~, it is used without checking the regular expressions. Otherwise the regular expressions (~, ~*) are tried in configuration order and the first one that matches wins. When none matches, the longest prefix is used.

Example

{
  "servers": [
    {
      "listen": [ { "port": 8080 } ],
      "locations": [
        { "match": "= /health", "return": { "status": 200, "body": "ok" } },
        { "match": "^~ /static/", "root": "www" },
        { "match": "~* \\.(png|jpe?g|gif|webp)$", "root": "www/images", "expires": "7d" },
        { "match": "/old/", "return": { "status": 301, "url": "https://example.com/new/" } },
        {
          "match": "/api/",
          "proxy_pass": "http://127.0.0.1:8081",
          "strip_prefix": true,
          "proxy_set_header": { "X-Real-IP": "$remote_addr", "X-Debug": "" },
          "proxy_hide_header": ["X-Powered-By"],
          "add_header": { "X-Frame-Options": "DENY" },
          "request_buffering": false,
          "client_max_body_size": "50m",
          "read_timeout": "120s",
          "allow": ["10.0.0.0/8"],
          "deny": ["0.0.0.0/0"]
        },
        { "match": "/", "proxy_pass": "http://127.0.0.1:8082/app" }
      ]
    }
  ]
}

More on the actions: Static Files, Proxy Cache, Compression and WebSocket Proxying.

6Guides

Load Balancing

A location with "proxy_pass": "<name>" sends its requests to the upstream <name>. The upstream spreads them over its servers with the method in balance.

balanceHow a server is chosen
round_robin (default)Smooth weighted round robin. A server with weight 3 gets three times the requests of a server with weight 1.
least_connThe server with the fewest active requests relative to its weight. Ties go by round robin.
ip_hashA hash of the client network (/24 for IPv4, /64 for IPv6), so a client keeps its server.
hashA hash of hash_key, for example $request_uri. With consistent it is a ketama ring.
{
  "upstreams": {
    "web": {
      "balance": "round_robin",
      "servers": [
        { "url": "http://10.0.0.11:8080", "weight": 3 },
        { "url": "http://10.0.0.12:8080" }
      ]
    },
    "sessions": {
      "balance": "ip_hash",
      "servers": [
        { "url": "http://10.0.0.21:8080" },
        { "url": "http://10.0.0.22:8080" }
      ]
    },
    "files": {
      "balance": "hash",
      "hash_key": "$request_uri",
      "consistent": true,
      "servers": [
        { "url": "http://10.0.0.31:8080" },
        { "url": "http://10.0.0.32:8080" },
        { "url": "http://10.0.0.33:8080" }
      ]
    }
  },
  "servers": [
    {
      "listen": [ { "port": 8080 } ],
      "locations": [
        { "match": "/app/", "proxy_pass": "sessions" },
        { "match": "/files/", "proxy_pass": "files" },
        { "match": "/", "proxy_pass": "web" }
      ]
    }
  ]
}

Details

Balancing and passive health follow nginx. round_robin is the smooth weighted round robin, least_conn takes the server with the fewest active requests relative to its weight (ties by round robin), ip_hash hashes the client /24 (IPv4) or /64 (IPv6), and hash hashes the expanded hash_key ($remote_addr, $request_uri, $http_<name> and the other proxy_set_header variables); with consistent it is a ketama ring, so removing one of n servers moves only about 1/n of the keys, without it adding or removing a server moves most keys. Backups are used only when every primary is down or already tried by the request.

After max_fails failures within fail_timeout (a connect error, a timeout, an invalid response head, or a 502, 503 or 504 that retry_on lists) a server is skipped for fail_timeout, then one trial request decides whether it is up again. When every server is down, the first one is tried anyway. A reload starts every upstream with fresh health state.

Keep-alive sizing

Keep-alive sizing: keepalive is the whole idle cache of each server of the upstream, shared by every worker thread of the process, and all servers of all upstreams together keep at most 4096 idle connections. nginx counts keepalive per worker process, so nginx keepalive 64 with 4 workers caches up to 256 connections per upstream, and the sgcProxy equivalent is keepalive: 256. Set it to about the peak number of requests in flight to one server: when more requests than keepalive finish together, the surplus connections are closed and the next burst opens new ones, which costs a connect per request and leaves a TIME_WAIT socket behind each close. A value above the need costs only idle sockets, which keepalive_timeout closes.

Active health checks

Active health checks (health_check, nginx Plus) probe every server of the upstream that is not down, every interval plus a small random jitter (the first probe comes at a random point of the first interval). One scheduler thread serves every upstream and at most 8 probes are in flight at a time. A probe is GET <path> HTTP/1.1 on a new connection, TLS with the tls settings of the upstream for https servers, with Host: <server host:port>, User-Agent: sgcProxy-health and Connection: close.

It succeeds when the status line arrives within timeout (connect, TLS handshake and status line together; the connect is also bounded by connect_timeout) with a status within expect_status. After fails consecutive failed probes the server is marked down, after passes consecutive good probes it is up again, and both changes go to the error log at warn level with the reason (the status, timeout or the connect error). Every server starts up, also after a reload, and a reload or a stop ends the probes of the old configuration within 1 s.

A server marked down by the health check is never chosen, not even by the all-down rule, and comes back only through good probes, which also clear its passive state; when every server is down by the health check or down, the request gets a 502. Passive health still applies between probes: a server that passes its probes is skipped for fail_timeout after max_fails failed requests and comes back by its trial request as usual. The all-down rule (try the first server anyway) only picks a server that is down passively.

This upstream retries failed requests on the next server, checks /ready every 2 seconds and keeps a backup server:

{
  "upstreams": {
    "api": {
      "balance": "least_conn",
      "keepalive": 256,
      "retries": 2,
      "retry_on": ["error", "timeout", "502", "503", "504"],
      "servers": [
        { "url": "http://10.0.0.41:8080", "max_fails": 2, "fail_timeout": "20s" },
        { "url": "http://10.0.0.42:8080", "max_fails": 2, "fail_timeout": "20s" },
        { "url": "http://10.0.0.43:8080", "backup": true }
      ],
      "health_check": { "path": "/ready", "interval": "2s", "timeout": "1s", "fails": 2, "passes": 2, "expect_status": 200 }
    }
  },
  "servers": [
    {
      "listen": [ { "port": 8080 } ],
      "locations": [
        { "match": "/", "proxy_pass": "api" }
      ]
    }
  ]
}

Retries only happen for idempotent requests whose body was not streamed yet. /status shows every server with its state, active requests, failures and last health check. The key reference is upstreams.

TLS and Post-Quantum Key Exchange

A listen entry with "tls": true serves HTTPS. The tls section holds the defaults of every TLS listener, and the tls object of each server holds its certificate.

Engines

  • native (default): the sgcWebSockets native TLS engine, written in Pascal and the same on Windows and Linux, so no OpenSSL libraries are needed. TLS 1.3 and 1.2 with AEAD ECDHE suites. HTTP/3 and the TLS-ALPN-01 challenge need this engine.
  • openssl: OpenSSL 3, loaded from the folder in tls.openssl.lib_path.

Versions

versions lists the TLS versions to accept, ["1.3", "1.2"] by default. ["1.3"] turns TLS 1.2 off.

Post-quantum key exchange

groups lists the key exchange groups in order of preference. The default list starts with X25519MLKEM768, a hybrid group that combines X25519 with ML-KEM-768, the module lattice key encapsulation mechanism of FIPS 203. A client that offers it gets a key exchange that combines both. A client that does not offer it negotiates the next group of the list that it supports, such as X25519, secp256r1 or secp384r1.

With the openssl engine and an OpenSSL version before 3.5, the ML-KEM groups are left out and a warning is logged.

This configuration accepts TLS 1.3 only and offers the hybrid group first:

{
  "tls": {
    "versions": ["1.3"],
    "groups": ["X25519MLKEM768", "X25519"]
  },
  "servers": [
    {
      "listen": [ { "port": 443, "tls": true, "default_server": true } ],
      "server_name": ["example.com", "www.example.com"],
      "tls": { "certificate": "certs/example.com.crt", "key": "certs/example.com.key" },
      "hsts": { "max_age": "730d", "include_subdomains": true, "preload": true },
      "locations": [
        { "match": "/", "proxy_pass": "http://127.0.0.1:8081" }
      ]
    }
  ]
}

Certificates and SNI

tls.certificate and tls.key of a server are PEM files, and both must exist. tls.password is the password of an encrypted key. On each handshake the certificate of the server that matches the SNI name is used, with the same server_name rules as the Host header. A handshake without SNI, or with an unknown name, gets the certificate of the default server of the listen entry. --test checks the certificate, the key, the expiry and the names.

A reload swaps the certificates for new connections, and open connections keep theirs. To get certificates automatically, see ACME Certificates.

HSTS

tls.hsts sets the Strict-Transport-Security header of every TLS server. The hsts object of a server overrides it with the same keys. max_age is a duration and is sent in seconds.

{
  "tls": {
    "engine": "native",
    "versions": ["1.3", "1.2"],
    "groups": ["X25519MLKEM768", "X25519", "secp256r1", "secp384r1"],
    "session_tickets": true,
    "hsts": { "max_age": "365d", "include_subdomains": false, "preload": false }
  },
  "servers": [
    {
      "listen": [ { "port": 443, "tls": true, "default_server": true } ],
      "server_name": ["example.com", "www.example.com"],
      "tls": { "certificate": "certs/example.com.crt", "key": "certs/example.com.key" },
      "locations": [
        { "match": "/", "proxy_pass": "http://127.0.0.1:8081" }
      ]
    }
  ]
}

Headers to the upstream

A request that arrived over TLS is forwarded with X-Forwarded-Proto: https. The key reference is tls.

HTTP/2 and HTTP/3

HTTP/2 and HTTP/3 are turned on per listen entry, next to HTTP/1.1. Both need "tls": true.

{
  "global": {
    "client_max_body_size": "100m"
  },
  "servers": [
    {
      "listen": [ { "port": 443, "tls": true, "http2": true, "http3": true, "default_server": true } ],
      "server_name": ["example.com", "www.example.com"],
      "tls": { "certificate": "certs/example.com.crt", "key": "certs/example.com.key" },
      "locations": [
        { "match": "/", "proxy_pass": "http://127.0.0.1:8081" }
      ]
    }
  ]
}

HTTP/2

Requires tls, h2c is not supported. ALPN offers h2 next to http/1.1. Limits: 128 concurrent streams per connection (the nginx default), the library defaults for the rest (64 KB initial window, 16 KB frames, 256 KB header list); no server push. A request with Upgrade or another connection-specific header (a WebSocket handshake over h2, RFC 8441 is not enabled) gets 400 as RFC 9113 8.2.2 requires, CONNECT gets 405

HTTP/2 responses stream with flow control, trailers and client cancel. Request bodies stream to the upstream under flow control, and client_max_body_size answers 413 early.

HTTP/3

Requires tls and the NativeTLS engine (a listener on OpenSSL keeps HTTP/3 off and logs a warning). HTTP/3 on the UDP port of the same number. A QUIC handshake gets the certificate of the server its SNI name selects, as on TCP (exact, wildcard, suffix and regex names, tls.certificate or tls.acme); no SNI or an unknown name gets the certificate of the default server of the listen entry.

Requests take the same path as h1 and h2 (router, firewall rules, WAF, limits, return, static files, proxy_pass, HSTS, access log with protocol HTTP/3.0); responses are streamed with backpressure and a cancelled stream closes the upstream connection. A request with Upgrade or another connection-specific header is refused (RFC 9114 4.2), CONNECT gets 405. While the QUIC endpoint runs, the h1 and h2 responses of every server on the listener carry Alt-Svc: h3=":<port>"; ma=86400 under the add_header status rules, unless the location sets Alt-Svc in its own add_header; there is no key for it.

Limits today: an h3 request has no client address (the access log and the address rules see none), and the firewall deny list is not checked when a QUIC connection is accepted. A certificate reload (configuration reload, ACME issuance or renewal) reaches new QUIC connections for every host too, open ones keep theirs

HTTP/3 uses UDP. Open the UDP port in the firewall of the host. On Windows the Setup task "Allow sgcproxy.exe through Windows Firewall" adds a UDP rule as well.

Request bodies

0 = unlimited. Checked early on h1, h2 and h3: a Content-Length above it gets 413 before any body byte is read, a body without one gets 413 as soon as it passes the limit, and on h2 and h3 the rest of the body is refused (RST_STREAM(NO_ERROR), STOP_SENDING) while the connection stays usable. h2 and h3 request bodies stream to the upstream under flow control (chunked when the client sends no length), so an upload holds no more than the stream window; HTTP/3 streaming needs the native TLS engine. The HTTP/2 and HTTP/3 servers also get the largest limit of the configuration as their own; a reload that changes it reaches HTTP/3 after a restart (a warning is logged)

The key reference is [servers[].listen](@r_listen).

ACME Certificates

sgcProxy can get and renew its certificates from a CA that speaks ACME (RFC 8555), for example Let's Encrypt. You need three things:

  1. An acme section with the directory URL of the CA.
  2. "tls": { "acme": true } in every server that needs a certificate, with exact names in server_name.
  3. For the HTTP-01 challenge (the default), a plain listener on port 80 that serves the names. For TLS-ALPN-01, port 443 of the names must reach a TLS listener.
{
  "acme": {
    "directory": "https://acme-v02.api.letsencrypt.org/directory",
    "email": "admin@example.com",
    "storage": "certs",
    "renew_before": "30d",
    "check_interval": "12h",
    "challenge": "http-01"
  },
  "servers": [
    {
      "listen": [ { "port": 80 } ],
      "server_name": ["example.com", "www.example.com"],
      "locations": [
        { "match": "/", "return": { "status": 301, "url": "https://$host$request_uri" } }
      ]
    },
    {
      "listen": [ { "port": 443, "tls": true, "http2": true } ],
      "server_name": ["example.com", "www.example.com"],
      "tls": { "acme": true },
      "locations": [
        { "match": "/", "proxy_pass": "http://127.0.0.1:8081" }
      ]
    }
  ]
}

The redirect to https does not get in the way: the challenge path is answered before the location routing.

Certificates and renewal

Certificates. Every server with "tls": {"acme": true} gets one certificate, stored in storage/<name>/, where <name> is its first server_name; the certificate covers all its server_name entries. Wildcard (*.a.com), suffix (.a.com) and regex (~...) names need the DNS-01 challenge, which is not supported: --test, Start and Reload reject them with the path of the name (servers[0].server_name[1]), and a server with acme needs at least one exact name.

At start a valid stored certificate is served at once. Otherwise it is issued on a background thread, so the start and the other hosts are not held up; until it succeeds, handshakes for that host get the default certificate of the listener (the default server of the listen, when it has one) or fail, and the error log says so at warn level. A TLS listener whose default server has no certificate yet opens with a self-signed placeholder in storage/_placeholder/, which is never served for a host.

The manager checks every certificate every check_interval with the ACME Renewal Information and renew_before, writes the new files and swaps the certificate in for new handshakes without a restart; open connections keep the certificate they got. A failed order is retried after 1 hour, doubling up to 24 hours, or after the Retry-After of the CA when that is longer (at most 7 days). Stop and Reload cancel the ACME requests in flight and wait for the thread; a Reload that changes the acme section or the names of an acme server starts a new manager, any other Reload keeps the running one.

Storage

The account key and every certificate key are EC P-256 (ES256 for the account, ecdsa-with-SHA256 in the CSR). storage holds account.key (the account key, SEC1 PEM), account.json (the account URL for directory) and one folder per certificate with fullchain.pem and privkey.pem. Every file is written to a temporary file and then renamed.

On Linux the key files are created with mode 600; on Windows they inherit the ACL of the folder, so give storage to the service account only. Renewal follows the ACME Renewal Information of the CA (RFC 9773) when its directory offers renewalInfo, otherwise renew_before applies. eab.hmac_key is the base64url key the CA gives.

HTTP-01

HTTP-01. Every plain HTTP listener answers GET /.well-known/acme-challenge/<token> itself, before the location routing and so before a redirect to https, like the usual nginx setup: 200 with text/plain and the key authorization for a pending token, 404 for an unknown one. The token must be base64url (A-Z a-z 0-9 - _, 1 to 256 characters), anything else is a 404.

This path skips the WAF and the rate limits; the connection checks of the firewall still apply. The CA connects on port 80, so a plain listener on port 80 must serve the names. When no server has acme, the path is routed like any other.

TLS-ALPN-01

TLS-ALPN-01 (RFC 8737), "challenge": "tls-alpn-01": the CA connects to port 443 of every name with the name as SNI and only the ALPN acme-tls/1. While the authorization is pending, the native TLS listeners answer that handshake with a self-signed challenge certificate (EC P-256, the name as subjectAltName, the critical acmeIdentifier extension holding the SHA-256 of the key authorization), negotiate acme-tls/1 and close the connection without serving a request. Every other client gets the normal certificate and h2 or http/1.1.

The challenge certificate is dropped when the authorization is over. It needs tls.engine native (with openssl it is a configuration error) and a listen entry with "tls": true in every server with "tls": {"acme": true}, and port 443 of the names must reach that listener, directly or forwarded. No plain listener on port 80 is needed.

With tls.engine openssl, every name gets the certificate the listener loaded at start or reload.

{
  "acme": {
    "directory": "https://acme.example.net/directory",
    "email": "admin@example.com",
    "challenge": "tls-alpn-01",
    "eab": { "kid": "kid-1", "hmac_key": "c2VjcmV0LWtleS1mcm9tLXRoZS1jYQ" }
  },
  "servers": [
    {
      "listen": [ { "port": 443, "tls": true } ],
      "server_name": ["example.com"],
      "tls": { "acme": true },
      "locations": [
        { "match": "/", "proxy_pass": "http://127.0.0.1:8081" }
      ]
    }
  ]
}

Monitoring

/status lists every certificate with its expiry, the next renewal check and the failures. The key reference is acme.

Static Files

A location with root or alias serves files from a folder. The behaviour follows nginx: index files, try_files with internal redirects, autoindex, MIME types, ETag and Last-Modified with 304 and 412, byte ranges (206, multipart/byteranges, 416, If-Range), HEAD and 405 for other methods. Files are streamed in 64 KB reads, also above 4 GB. Path traversal, symbolic links and junctions are checked.

root and alias

  • root: the file is the folder plus the full URI. With "root": "www", /static/site.css is www/static/site.css.
  • alias: the matched prefix is replaced by the folder. With "match": "/downloads/" and "alias": "files/", /downloads/a.zip is files/a.zip.

Relative folders resolve against the folder of the configuration file.

{
  "servers": [
    {
      "listen": [ { "port": 8080 } ],
      "locations": [
        {
          "match": "/",
          "root": "www",
          "index": ["index.html", "index.htm"],
          "try_files": ["$uri", "$uri/", "/index.html"],
          "types": { "text/markdown": ["md", "markdown"] },
          "default_type": "application/octet-stream",
          "expires": "1h",
          "log_not_found": false
        },
        { "match": "/downloads/", "alias": "files/", "autoindex": true },
        { "match": "^~ /assets/", "root": "www", "expires": "max", "add_header": { "X-Content-Type-Options": "nosniff" } }
      ]
    }
  ]
}

The first location is a single page application: a path that is neither a file nor a folder is answered with /index.html.

MIME types

The nginx mime.types table is built in. types adds or changes entries for one location, merged over the built-in table, and default_type is the type of an extension that no table lists.

expires

expires follows nginx on the statuses 200, 201, 204, 206, 301, 302, 303, 304, 307 and 308. epoch sends Expires: Thu, 01 Jan 1970 00:00:01 GMT and Cache-Control: no-cache, max sends Expires: Thu, 31 Dec 2037 23:55:55 GMT and Cache-Control: max-age=315360000, a duration sends Expires at now plus the duration and Cache-Control: max-age=<seconds>, and a negative duration sends Cache-Control: no-cache.

The key reference is [servers[].locations](@r_loc).

Proxy Cache

The proxy cache stores upstream responses on disk and answers later requests from there. Define a zone in caches and add a cache object to a proxy_pass location:

{
  "global": {
    "admin": { "listen": "127.0.0.1:8099" }
  },
  "caches": {
    "pages": { "path": "cache/pages", "max_size": "1g", "inactive": "1d", "default_ttl": 0, "key": "$scheme$host$request_uri", "max_entries": 100000 }
  },
  "servers": [
    {
      "listen": [ { "port": 8080 } ],
      "locations": [
        {
          "match": "/",
          "proxy_pass": "http://127.0.0.1:8081",
          "cache": {
            "zone": "pages",
            "methods": ["GET", "HEAD"],
            "valid": { "200 302": "10m", "404": "1m" },
            "use_stale": ["error", "timeout", "updating", "http_502", "http_503"],
            "lock_timeout": "5s",
            "bypass": ["$cookie_nocache", "$arg_nocache"],
            "no_cache": ["$http_pragma"],
            "status_header": true,
            "set_cookie": false
          }
        }
      ]
    }
  ]
}

Zones

"caches": { "<name>": { ... } }. nginx proxy_cache_path.

The zone keeps an in-memory index of its entries and two files per entry in path: the body (.dat) and a header file (.hdr). A body is written to a .tmp file while it streams to the client and renamed when it is complete, and the header file is written last, so a partial entry is never served. When the zone opens (start, or a reload that adds it), the index is rebuilt from the header files and leftover .tmp files are removed.

A sweeper thread removes the entries not read for inactive and evicts the least recently used ones while the zone is above max_size or max_entries, every second and at once after a store that went above a limit. A reload keeps a zone with the same name and path (new limits apply), and a zone whose folder cannot be created is not cached.

Behaviour

  • Lookup: the key is cache.key, else the zone key. A fresh entry answers without the upstream (HIT). HEAD is answered from a GET entry, and a HEAD miss is forwarded as HEAD and not stored. A single byte range of a cached 200 is answered as 206 from the entry (416 when it starts after the end; several ranges get the whole 200), and the client's If-None-Match and If-Modified-Since get a 304 from the entry. These client fields and Range are not sent to the upstream.
  • Not stored: Cache-Control: no-store or private, Vary: *, Set-Cookie (unless cache.set_cookie), a request with Authorization unless the response has public, s-maxage or must-revalidate, and 206 and 304 responses.
  • Freshness: s-maxage, then max-age, then Expires minus Date, then cache.valid (the status, then any), then cache.ttl or the zone default_ttl for 200, 301 and 302, minus Age. A response without a freshness is not stored. Cache-Control: no-cache stores it, and it is revalidated before every use.
  • Vary: one entry per value set of the varied request fields.
  • A stale entry is revalidated with If-None-Match (its ETag) and If-Modified-Since (its Last-Modified). A 304 refreshes the entry and answers from it (REVALIDATED), a new response replaces it (EXPIRED).
  • Miss collapsing: one upstream request per key while it fills. The other requests wait up to cache.lock_timeout and then get the new entry, or go to the upstream without storing (MISS). With use_stale updating they get the stale entry at once (UPDATING).
  • Stale answers (STALE): use_stale error (the upstream cannot be connected or sends no valid head), timeout, and http_500, http_502, http_503, http_504. The stale-if-error of the response also allows it for its time. Never after must-revalidate or proxy-revalidate.
  • X-Cache-Status is HIT, MISS, EXPIRED, STALE, UPDATING, BYPASS or REVALIDATED (off with cache.status_header: false). Answers from the cache carry Age.
  • The body is stored while it streams to the client, never buffered whole, and the entry is complete before the last byte reaches the client.
  • Purge: POST /cache/purge on the admin listener, with key=<cache key> (all its variants) or prefix=<start of the key>, and optionally zone=<name> (default all zones), URL encoded, in the query string or in an application/x-www-form-urlencoded body (the query string wins). With the default key, /c/a on example.com over http is the key httpexample.com/c/a. The answer is JSON, {"purged": <count>}, 400 without key and prefix, 404 for an unknown zone, 405 for another method.
  • Counters: /status has caches with hits, misses, bytes, entries and max_size per zone, and /metrics has sgcproxy_cache_hits_total{zone}, sgcproxy_cache_misses_total{zone}, sgcproxy_cache_bytes{zone} and sgcproxy_cache_entries{zone}. Hits count HIT, STALE, UPDATING and REVALIDATED; misses count MISS, EXPIRED and BYPASS. They start when the zone opens.

Purge

POST /cache/purge on the admin listener removes entries. The parameters go in the query string or in an application/x-www-form-urlencoded body, URL encoded: key=<cache key> removes that key with all its variants, prefix=<start of the key> removes every key that starts with it, and zone=<name> limits the purge to one zone (all zones by default). When the query string and the body both have a field, the query string wins. With any other Content-Type the body is ignored and only the query string counts. The body may be at most 8192 bytes: a larger Content-Length, or a chunked body, gets 413 before the body is read.

curl -X POST "http://127.0.0.1:8099/cache/purge?prefix=httpexample.com/catalog/"
curl -X POST "http://127.0.0.1:8099/cache/purge?key=httpexample.com/c/a&zone=pages"
curl --data-urlencode "key=httpexample.com/c/a" --data-urlencode "zone=pages" http://127.0.0.1:8099/cache/purge
StatusBody
200{"purged":<count>}
400{"error":"key or prefix is required"}
404{"error":"unknown cache zone"}
405Any method other than POST.
413request body too large, at most 8192 bytes (text), for a body above 8192 bytes or a chunked body.

Per location key and TTL

A location can override the key and the TTL, and skip the cache for requests that carry a header:

{
  "caches": {
    "api": { "path": "cache/api", "max_size": "256m", "inactive": "1h", "default_ttl": "1m" }
  },
  "servers": [
    {
      "listen": [ { "port": 8080 } ],
      "locations": [
        {
          "match": "/catalog/",
          "proxy_pass": "http://127.0.0.1:8081",
          "cache": { "zone": "api", "ttl": "5m", "key": "$host$uri$arg_page", "bypass_header": "X-No-Cache" }
        }
      ]
    }
  ]
}

The key references are caches and the cache keys of [servers[].locations](@r_loc).

Compression

gzip in a location compresses its responses: static files, proxied responses and responses of return. The keys follow nginx gzip, gzip_types, gzip_min_length, gzip_comp_level, gzip_proxied and gzip_vary.

{
  "servers": [
    {
      "listen": [ { "port": 8080 } ],
      "locations": [
        {
          "match": "/events",
          "proxy_pass": "http://127.0.0.1:8081",
          "buffering": false,
          "gzip": { "enabled": true, "types": ["text/event-stream"] }
        },
        {
          "match": "/",
          "proxy_pass": "http://127.0.0.1:8081",
          "gzip": {
            "enabled": true,
            "types": ["text/html", "text/css", "application/javascript", "application/json", "image/svg+xml"],
            "min_length": "1k",
            "level": 5,
            "proxied": ["expired", "no-cache", "no-store", "private", "auth"],
            "vary": true
          }
        }
      ]
    }
  ]
}

The first location compresses server-sent events. text/event-stream is not in the default gzip.types, so it is listed there.

Rules

gzip follows nginx. A response is compressible when its status is 200, 403 or 404, it has no Content-Encoding, its Content-Type is text/html or in gzip.types, and its Content-Length is unknown or at least gzip.min_length. HEAD requests and 206 or 304 responses are never compressed.

gzip.vary adds Vary: Accept-Encoding to every compressible response. The client must speak HTTP/1.1 and list gzip in Accept-Encoding with a q-value above 0, and a request with Via is compressed only as gzip.proxied allows. A compressed response is sent chunked without Content-Length and Accept-Ranges, and a strong ETag becomes weak.

Every write is flushed as a gzip block, so a streamed response still streams. text/event-stream is not in the default gzip.types: add it to compress server-sent events. A body that ends with the connection (neither Content-Length nor chunked) is not compressed.

When try_files moves a request to another location, the gzip settings of the first location apply.

The key reference is [servers[].locations](@r_loc).

Firewall and Rate Limiting

The firewall section protects every listener: address lists, trusted proxies, a WAF, flood protection, GeoIP and bans that survive restarts. Rate limits are separate zones in limits that a location uses with limit.

{
  "firewall": {
    "allow": [],
    "deny": ["203.0.113.0/24", "2001:db8:bad::/48"],
    "trusted_proxies": ["10.0.0.0/8"],
    "forwarded_mode": "x-forwarded-for",
    "trusted_hops": 1,
    "waf": { "sql_injection": true, "xss": true, "path_traversal": true, "command_injection": true },
    "waf_headers": ["User-Agent", "Referer", "Cookie"],
    "flood": { "max_requests_per_second": 100 },
    "bot_detection": false,
    "bans_file": "logs/bans.dat"
  },
  "limits": {
    "api": { "strategy": "token_bucket", "rate": 10, "per": "second", "burst": 20, "key": "ip", "status": 429, "retry_after": true }
  },
  "servers": [
    {
      "listen": [ { "port": 8080 } ],
      "locations": [
        { "match": "/api/", "proxy_pass": "http://127.0.0.1:8081", "limit": "api" },
        { "match": "/", "proxy_pass": "http://127.0.0.1:8081" }
      ]
    }
  ]
}

Address lists and trusted proxies

A client that deny lists, or that allow does not list, is refused when it connects: the connection is closed with no response, on every listener (HTTP/1.1 and HTTP/2 share the socket). Behind a trusted_proxies peer the client comes from the forwarded header; when deny lists that client, the connection is closed with no response, or a later request on the same connection gets 403. The header of any other peer is ignored.

With a waf check or flood on, the target of every request (path and query, percent-decoded once, + in the query read as a space) is inspected after the ACME HTTP-01 path and before the location routing, over HTTP/1.1 and HTTP/2. A match gets 403, the upstream is not contacted, and the error log gets one warn line next to the access line. Request headers are not inspected.

brute_force needs failed attempts, which sgcProxy does not report yet, so it has no effect today. A reload builds a new firewall for new connections and keeps its bans; requests in flight finish with the old one.

WAF

The WAF (waf) inspects the request target, percent-decoded once, and then every value of the headers that waf_headers names (case-insensitive): the first 8 KB of each value, percent-decoded once. A match gets 403 on HTTP/1.1, HTTP/2 and HTTP/3, one warn line in the error log and an access line, and counts in waf_blocked of /status and sgcproxy_waf_blocked_total{location_kind} of /metrics (target or header; a target refused by flood counts as target). The header values run on a firewall of their own with the WAF checks only, so a request counts once for flood.

An HTTP/3 client is not checked when its QUIC connection is accepted: its address (the RemoteIP of the QUIC connection) goes through allow and deny on every request instead, and a refused one gets 403.

Per server and per location lists

allow and deny of a server or a location limit the clients of that server or location only.

Rate limits

"limits": { "<name>": { ... } }. Maps onto TsgcWSRateLimiter. nginx limit_req_zone / limit_req.

A location with limit takes one request from its zone, keyed by the client address (after trusted_proxies), the X-API-Key header for api_key, or the named header; a request without the key is counted under its client address. A request with no client address at all (an HTTP/3 engine that reports none) is counted under the key ip:unknown, one bucket for all such requests, and the first one logs a warning. A throttled request gets status, with Retry-After in whole seconds (at least 1) when retry_after is on, one warn line in the error log and an access line, and the connection is closed.

The zones are shared by every listener. A reload starts new zones, so their counters start again.

{
  "limits": {
    "api": { "strategy": "token_bucket", "rate": 10, "per": "second", "burst": 20 },
    "partners": { "strategy": "sliding_window", "rate": 600, "per": "minute", "key": "header:X-Partner-Id", "status": 503, "retry_after": false },
    "login": { "strategy": "fixed_window", "rate": 5, "per": "minute", "key": "ip" },
    "keys": { "rate": 1000, "per": "hour", "key": "api_key" }
  },
  "servers": [
    {
      "listen": [ { "port": 8080 } ],
      "locations": [
        { "match": "= /login", "proxy_pass": "http://127.0.0.1:8081", "limit": "login" },
        { "match": "/api/", "proxy_pass": "http://127.0.0.1:8081", "limit": "api" },
        { "match": "/partners/", "proxy_pass": "http://127.0.0.1:8081", "limit": "partners" },
        { "match": "/v2/", "proxy_pass": "http://127.0.0.1:8081", "limit": "keys" }
      ]
    }
  ]
}

The key references are firewall and limits.

WebSocket Proxying

sgcProxy proxies WebSocket connections like nginx with proxy_http_version 1.1 and the Upgrade and Connection headers. Nothing extra is needed: websocket is true by default on every proxy_pass location.

How it works

  • A GET HTTP/1.1 upgrade on a location with websocket is forwarded with Upgrade and Connection: upgrade on a new upstream connection. It is never retried once sent.
  • A 101 answer with Upgrade: websocket is relayed, and both connections become a raw two way tunnel. Any other status is a normal response.
  • A close on either side closes both. The read_timeout closes an idle tunnel, and the upstream send_timeout bounds a stalled write.
  • The upstream connection is handed to the IOCP or EPOLL engine of the listener, so an idle tunnel holds no thread. OpenSSL upstreams, TLS upstreams behind a plain listener and listeners without an engine keep one reader thread per tunnel.
  • A location with "websocket": false strips Upgrade, so the upgrade is not passed on. A body with an upgrade gets 400.
  • A reload keeps open tunnels on their configuration. A stop closes the tunnels after drain_timeout.
  • The access log gets one line per tunnel when it closes: status 101, the bytes sent to the client and the duration as the request time.
{
  "upstreams": {
    "chat": {
      "servers": [ { "url": "http://127.0.0.1:9000" } ],
      "send_timeout": "30s",
      "read_timeout": "1h"
    }
  },
  "servers": [
    {
      "listen": [ { "port": 443, "tls": true } ],
      "server_name": ["example.com"],
      "tls": { "certificate": "certs/example.com.crt", "key": "certs/example.com.key" },
      "locations": [
        { "match": "/ws/", "proxy_pass": "chat", "websocket": true, "read_timeout": "10m" },
        { "match": "/", "proxy_pass": "http://127.0.0.1:8081", "websocket": false }
      ]
    }
  ]
}

HTTP/2 and HTTP/3

WebSocket over HTTP/2 (RFC 8441) is not enabled. On an HTTP/2 connection a request with Upgrade gets 400, and HTTP/3 refuses it too, so WebSocket clients connect over HTTP/1.1. /status counts the open tunnels in connections.tunnels, and /metrics has sgcproxy_tunnels_active.

Status Page and Prometheus Metrics

With global.admin set, the admin listener serves GET /status and GET /metrics on a loopback address. Only the clients in admin.allow get an answer, all others get 403.

{
  "global": {
    "admin": { "listen": "127.0.0.1:8099", "allow": ["127.0.0.1", "::1"] }
  },
  "servers": [
    {
      "listen": [ { "port": 8080 } ],
      "locations": [
        { "match": "/", "proxy_pass": "http://127.0.0.1:8081" }
      ]
    }
  ]
}
curl http://127.0.0.1:8099/status
curl http://127.0.0.1:8099/metrics

/status

/status is JSON. This is the answer of a proxy with one plain listener, after two requests:

{
  "version": "2026.12.0",
  "state": "running",
  "uptime": 0,
  "generation": 1,
  "listeners": [
    {
      "address": "127.0.0.1",
      "port": 18080,
      "tls": false,
      "http2": false,
      "http3": false,
      "connections": 0,
      "in_flight": 0,
      "async": {
        "enabled": true,
        "in_flight": 0,
        "links": 0,
        "idle": 0,
        "created": 1,
        "reused": 0,
        "closed": 1
      }
    }
  ],
  "connections": {
    "active": 0,
    "idle": 0,
    "in_flight": 0,
    "tunnels": 0
  },
  "requests": {
    "total": 2,
    "1xx": 0,
    "2xx": 2,
    "3xx": 0,
    "4xx": 0,
    "5xx": 0
  },
  "upstreams": [],
  "acme": [],
  "reloads": {
    "success": 0,
    "failed": 0,
    "last_error": "",
    "last_time": null
  },
  "waf_blocked": {
    "target": 0,
    "header": 0
  },
  "caches": {}
}
FieldContent
version, stateThe version and the state of the engine.
uptimeSeconds since the start.
generationOne more per start and per successful reload.
listenersPer listener: address, port, tls, http2, http3 (HTTP/3 active), connections and requests in flight.
listeners[].asyncThe event pool of the listener: enabled when the listener runs the event driven forward, its requests in_flight, its upstream links and idle links, and the links created, reused and closed.
connectionsactive, idle (idle keep-alive), in_flight and tunnels.
requeststotal and one counter per status class.
upstreamsEvery upstream server with its state (up, down or backup), active requests, failures and last health check.
acmePer certificate: the expiry, the next renewal check and the failures.
reloadssuccess, failed, last_error and last_time.
waf_blockedRequests the WAF refused, by target and header.
cachesPer zone: hits, misses, bytes, entries and max_size.

/metrics

/metrics is the Prometheus text format 0.0.4. The counters are atomic increments, kept for the life of the process.

MetricTypeContent
sgcproxy_requests_total{server,status_class,protocol}counterRequests answered.
sgcproxy_upstream_requests_total{upstream,server,result}counterRequests sent to upstream servers.
sgcproxy_request_duration_secondshistogramRequest duration, buckets from 5 ms to 10 s.
sgcproxy_connections_active{protocol}gaugeOpen connections. tcp covers HTTP/1.1, HTTP/2 and tunnels.
sgcproxy_tunnels_activegaugeOpen WebSocket and CONNECT tunnels.
sgcproxy_async_in_flight{address,port}gaugeRequests in flight on the event driven forward of a listener.
sgcproxy_event_pool_links{address,port}gaugeUpstream links of the event pool of a listener.
sgcproxy_event_pool_idle{address,port}gaugeIdle links of the event pool.
sgcproxy_event_pool_created_total, sgcproxy_event_pool_reused_total, sgcproxy_event_pool_closed_total {address,port}counterLinks created, reused and closed by the event pool.
sgcproxy_upstream_up{upstream,server}gauge1 when the server is up.
sgcproxy_reloads_total{result}counterReloads that succeeded and failed.
sgcproxy_waf_blocked_total{location_kind}counterRequests the WAF refused, target or header.
sgcproxy_config_generationgaugeThe generation of /status.
sgcproxy_uptime_secondsgaugeSeconds since the start.
sgcproxy_cache_hits_total{zone}, sgcproxy_cache_misses_total{zone}counterCache hits and misses per zone.
sgcproxy_cache_bytes{zone}, sgcproxy_cache_entries{zone}gaugeSize and entries of a cache zone.

The event pool metrics have one sample per listener that runs the event driven forward. The cache metrics are listed only when the configuration has cache zones.

The server label is the first server_name of the server that took the request (_ when it has none). At most 64 server names and 256 upstream servers get their own labels, the rest count as _other. No label holds a path or a client address. Not counted yet: tunnels in sgcproxy_requests_total, and HTTP/3 connections in sgcproxy_connections_active.

Prometheus

The admin listener accepts loopback clients only, so run Prometheus, or an agent that forwards the samples, on the same host:

scrape_configs:
  - job_name: sgcproxy
    static_configs:
      - targets: ["127.0.0.1:8099"]

The key reference is global.admin.

Event Driven Forward

On the IOCP engine (Windows) and the EPOLL engine (Linux), a proxied HTTP/1.1 request that qualifies is forwarded event driven: no worker thread waits while the upstream answers. The upstream connection is adopted into the engine of the listener and pooled per listener. The response is relayed from the engine threads, and one sweeper thread handles the read timeouts, client probes and idle links. A request in flight holds no thread. It is off by default: set global.proxy_async to true to turn it on.

Which requests take it

An HTTP/1.1 request to a proxy_pass location on a listener that runs the IOCP or EPOLL engine. These requests take the blocking forward instead:

  • HTTP/2 and HTTP/3 requests.
  • WebSocket upgrades to a location with websocket on.
  • Requests with a chunked request body.
  • Requests with a Content-Length body above 64 KB (65536 bytes), or with a body that has not been received in full when the request is routed.
  • Requests with an Expect header, such as Expect: 100-continue.
  • Pipelined requests: the connection already holds more data than the request and its body.
  • Any request when the connection limit of the listener is reached. That limit covers the client connections plus the pooled upstream connections.

A location with a cache takes the event driven forward as well; a fresh cache hit is still answered from the cache without an upstream request.

Retries, error pages, passive health and the access and error log lines are the same on both paths.

Turning it on

global.proxy_async is false by default, so every request goes through the blocking forward. Set it to true to turn on the event driven forward:

{
  "global": {
    "proxy_async": true,
    "admin": { "listen": "127.0.0.1:8099" }
  },
  "servers": [
    {
      "listen": [ { "port": 8080 } ],
      "locations": [
        { "match": "/", "proxy_pass": "http://127.0.0.1:8081" }
      ]
    }
  ]
}

The value is read per request from the running configuration, so a reload switches it for the next requests. No restart is needed.

Monitoring

/status shows the event pool of every listener in listeners[].async, for example:

"async": { "enabled": true, "in_flight": 0, "links": 0, "idle": 0, "created": 1, "reused": 0, "closed": 1 }

/metrics has sgcproxy_async_in_flight, sgcproxy_event_pool_links, sgcproxy_event_pool_idle and the counters sgcproxy_event_pool_created_total, sgcproxy_event_pool_reused_total and sgcproxy_event_pool_closed_total, labelled with the address and port of the listener. See Status Page and Prometheus Metrics.

Stop and reload

On a stop, and for a listener that a reload removes, the requests on the event path count as in flight for drain_timeout. Then they are aborted, the upstream connections are closed and the listener closes.

Logging

sgcProxy writes two logs: the error log for events and problems, and the access log with one line per request. Both are written by a background thread from a bounded in-memory queue.

Error log

global.error_log.path is the file, logs/error.log by default, or "-" for standard output. level is debug, info, notice, warn (default) or error. The lines use the nginx format: date and time, level, process id and thread id, message.

2026/11/27 02:12:00 [info] 17472#23652: engine started, configuration C:\ProgramData\eSeGeCe\sgcProxy\sgcproxy.json loaded (1 servers, 0 upstreams), 1 listeners
2026/11/27 02:12:00 [info] 17472#23652: listening on http://127.0.0.1:18080
2026/11/27 02:12:00 [info] 17472#23652: admin listener (/status, /metrics) on http://127.0.0.1:18099, [::1]:18099

On Windows the warn and error lines, and a failed start, also go to the Application event log. On Linux the systemd unit sends standard output to the journal, so the starter configuration writes the error log to "-" and you read it with journalctl -u sgcproxy.

Access log

global.access_log.path is the file, logs/access.log by default, "-" for standard output or "off" for no access log. format is combined (default) or json.

The combined format is the nginx combined line followed by the request time in seconds and the upstream address ("-" when the request did not go upstream). When a request tried several upstream servers, every one is listed.

127.0.0.1 - - [27/Nov/2026:02:12:03 +0100] "GET / HTTP/1.1" 200 2 "-" "curl/8.22.0" 0.000 "-"
127.0.0.1 - - [27/Nov/2026:02:12:03 +0100] "GET /up/status HTTP/1.1" 200 548 "-" "curl/8.22.0" 0.002 "127.0.0.1:18099"

The json format writes one JSON object per line with the fields time, remote_addr, method, uri, protocol, status, bytes_sent, referer, user_agent, request_time, upstream_addr, upstream_status, upstream_time and host:

{"time":"2026-11-27T01:12:00.697Z","remote_addr":"127.0.0.1","method":"GET","uri":"/","protocol":"HTTP/1.1","status":200,"bytes_sent":2,"referer":"","user_agent":"curl/8.22.0","request_time":0.000,"upstream_addr":null,"upstream_status":null,"upstream_time":null,"host":"127.0.0.1:18080"}
{"time":"2026-11-27T01:12:00.732Z","remote_addr":"127.0.0.1","method":"GET","uri":"/up/status","protocol":"HTTP/1.1","status":200,"bytes_sent":548,"referer":"","user_agent":"curl/8.22.0","request_time":0.003,"upstream_addr":"127.0.0.1:18099","upstream_status":200,"upstream_time":0.000,"host":"127.0.0.1:18080"}

A WebSocket tunnel gets one line when it closes, with status 101. An HTTP/3 request has the protocol HTTP/3.0. A request refused by the WAF or a rate limit gets an access line and a warn line in the error log.

Examples

Error log to standard output at info level, access log as JSON:

{
  "global": {
    "error_log": { "path": "-", "level": "info" },
    "access_log": { "path": "logs/access.json", "format": "json" }
  },
  "servers": [ { "listen": [ { "port": 8080 } ], "locations": [ { "match": "/", "return": { "status": 200, "body": "ok" } } ] } ]
}

Errors only, no access log:

{
  "global": {
    "error_log": { "path": "logs/error.log", "level": "error" },
    "access_log": { "path": "off" }
  },
  "servers": [ { "listen": [ { "port": 8080 } ], "locations": [ { "match": "/", "return": { "status": 200, "body": "ok" } } ] } ]
}

Log rotation

  • Linux: rotate the files, then send SIGUSR1 (systemctl kill -s USR1 sgcproxy) to reopen them. See Installation on Linux.
  • Windows: rename the log file, then run sgcproxy.exe --reload, which also reopens the log files.

7Troubleshooting

sgcproxy --test prints the first problem it finds as sgcproxy: [emerg] <message> at <json path> in <file> and exits with code 1. The JSON path, for example servers[0].locations[1], points at the key to fix: the numbers count from 0. The messages below are the real output of --test for common mistakes.

Configuration errors

Invalid JSON

sgcproxy: [emerg] invalid JSON: Malformed JSON: trailing comma in array in C:\ProgramData\eSeGeCe\sgcProxy\sgcproxy.json

JSON allows no trailing comma and no comments. Check the commas around the line you changed last.

Duplicate key

sgcproxy: [emerg] invalid JSON: Malformed JSON: duplicate key "port" in C:\ProgramData\eSeGeCe\sgcProxy\sgcproxy.json

A key appears twice in the same object. Remove one of them.

Unknown key

sgcproxy: [emerg] unknown key "proxy_pas" at servers[0].locations[0].proxy_pas in C:\ProgramData\eSeGeCe\sgcProxy\sgcproxy.json

The key is misspelled or does not exist in that section. Every key is listed in the configuration reference, starting at Top Level Keys.

Wrong type

sgcproxy: [emerg] expected an integer, got a string "many" at global.keepalive_requests in C:\ProgramData\eSeGeCe\sgcProxy\sgcproxy.json

An integer key needs a JSON number. Sizes and durations accept a number or a string, see Value Types.

Value out of range

sgcproxy: [emerg] value 70000 is out of range 1..65535 at servers[0].listen[0].port in C:\ProgramData\eSeGeCe\sgcProxy\sgcproxy.json

The reference tables give the range of every number, size and duration.

Location without an action

sgcproxy: [emerg] missing action, a location needs one of proxy_pass, root, alias or return at servers[0].locations[0] in C:\ProgramData\eSeGeCe\sgcProxy\sgcproxy.json

Give the location one of proxy_pass, root, alias or return.

Two actions in one location

sgcproxy: [emerg] root conflicts with proxy_pass, a location has exactly one action at servers[0].locations[0].root in C:\ProgramData\eSeGeCe\sgcProxy\sgcproxy.json

A location has exactly one action. Split it into two locations with different matches.

Option of another action

sgcproxy: [emerg] strip_prefix is only valid with proxy_pass at servers[0].locations[0].strip_prefix in C:\ProgramData\eSeGeCe\sgcProxy\sgcproxy.json

Options such as strip_prefix belong to proxy_pass, and options such as try_files belong to root and alias. Remove the option or change the action.

Duplicate location

sgcproxy: [emerg] duplicate location "/", already at servers[0].locations[0] at servers[0].locations[1].match in C:\ProgramData\eSeGeCe\sgcProxy\sgcproxy.json

Two locations of a server have the same match. Merge them.

Upstream not defined

sgcproxy: [emerg] upstream "backend" is not defined at servers[0].locations[0].proxy_pass in C:\ProgramData\eSeGeCe\sgcProxy\sgcproxy.json

A proxy_pass value without http:// or https:// is an upstream name. Define the upstream in upstreams (in the main file or an included file), or write a URL.

Limit zone not defined

sgcproxy: [emerg] limit zone "api" is not defined at servers[0].locations[0].limit in C:\ProgramData\eSeGeCe\sgcProxy\sgcproxy.json

Define the zone in limits. The same applies to cache.zone and caches.

Upstream server URL with a path

sgcproxy: [emerg] invalid upstream server URL "http://127.0.0.1:8081/app", expected http(s)://host:port at upstreams.app.servers[0].url in C:\ProgramData\eSeGeCe\sgcProxy\sgcproxy.json

An upstream server is http(s)://host:port only. To change the path sent upstream, use strip_prefix, or proxy_pass with a URL that has a path.

hash_key without hash

sgcproxy: [emerg] hash_key is only valid when balance is hash at upstreams.app.hash_key in C:\ProgramData\eSeGeCe\sgcProxy\sgcproxy.json

Set "balance": "hash", or remove hash_key and consistent.

Included file not found

sgcproxy: [emerg] included file not found: C:\ProgramData\eSeGeCe\sgcProxy\sites\shop.json at include[0] in C:\ProgramData\eSeGeCe\sgcProxy\sgcproxy.json

The path is relative to the folder of the main file. A wildcard such as conf.d/*.json with no match is not an error.

Certificate file not found

sgcproxy: [emerg] file not found: C:\ProgramData\eSeGeCe\sgcProxy\certs\missing.crt at servers[0].tls.certificate in C:\ProgramData\eSeGeCe\sgcProxy\sgcproxy.json

Relative paths resolve against the folder of the main configuration file. On Linux the sgcproxy user must be able to read the file.

GeoIP database not found or empty

sgcproxy: [emerg] file not found: C:\ProgramData\eSeGeCe\sgcProxy\geoip\countries.csv at firewall.geoip.database in C:\ProgramData\eSeGeCe\sgcProxy\sgcproxy.json
sgcproxy: [emerg] file is empty: C:\ProgramData\eSeGeCe\sgcProxy\geoip\countries.csv at firewall.geoip.database in C:\ProgramData\eSeGeCe\sgcProxy\sgcproxy.json

firewall.geoip.database must name a file that exists, can be opened for reading and is not empty. A file that exists but cannot be opened gives file cannot be read: with the path and the system error. A relative path is resolved against the folder of the configuration file. The check runs on --test, at the start and on every reload; the content of the file is checked by the GeoIP loader when the firewall starts.

OpenSSL libraries not found

sgcproxy: [emerg] OpenSSL 3 libraries not found in C:\ProgramData\eSeGeCe\sgcProxy\openssl: libcrypto-3-x64.dll, libssl-3-x64.dll at tls.openssl.lib_path in C:\ProgramData\eSeGeCe\sgcProxy\sgcproxy.json
sgcproxy: [emerg] folder not found: C:\ProgramData\eSeGeCe\sgcProxy\openssl at tls.openssl.lib_path in C:\ProgramData\eSeGeCe\sgcProxy\sgcproxy.json

tls.openssl.lib_path must be a folder that holds the OpenSSL 3 libraries the listeners load: libcrypto-3-x64.dll and libssl-3-x64.dll on Windows, libcrypto.so.3 and libssl.so.3 on Linux. The message lists the ones that are missing. The check is by file name; a library that is present but cannot be loaded fails when a listener with "engine": "openssl" starts.

TLS listener without a certificate

sgcproxy: [emerg] missing required key "tls", a listen entry has tls: give certificate and key, or acme at servers[0].tls in C:\ProgramData\eSeGeCe\sgcProxy\sgcproxy.json

A server with a "tls": true listen entry needs a tls object with certificate and key, or "acme": true.

Port used with and without TLS

sgcproxy: [emerg] port 8443 is declared plain here and tls at servers[0].listen[0] in C:\ProgramData\eSeGeCe\sgcProxy\sgcproxy.json at servers[1].listen[0] in C:\ProgramData\eSeGeCe\sgcProxy\sgcproxy.json

A port is either TLS or plain in every server that listens on it. Use another port for one of them.

HTTP/2 without TLS

sgcproxy: [emerg] http2 requires tls at servers[0].listen[0].http2 in C:\ProgramData\eSeGeCe\sgcProxy\sgcproxy.json

h2c is not supported. Add "tls": true to the listen entry, or remove http2.

ACME not configured

sgcproxy: [emerg] acme is not configured, add the top-level "acme" section at servers[0].tls.acme in C:\ProgramData\eSeGeCe\sgcProxy\sgcproxy.json

Add the top level acme section with the directory of your CA.

Wildcard name with ACME

sgcproxy: [emerg] server_name "*.example.com" cannot get an ACME certificate: wildcard, suffix and regex names need the DNS-01 challenge, which is not supported; list the exact names at servers[0].server_name[1] in C:\ProgramData\eSeGeCe\sgcProxy\sgcproxy.json

ACME certificates need exact names. List every name, or use a certificate file for the wildcard.

Admin listener on a public address

sgcproxy: [emerg] the admin listener must be bound to a loopback address (127.0.0.1 or ::1), not "0.0.0.0" at global.admin.listen in C:\ProgramData\eSeGeCe\sgcProxy\sgcproxy.json

The admin listener binds a loopback address only, for example 127.0.0.1:8099.

Other problems

The service cannot be registered

--install and --uninstall print The service could not be registered: run the command as administrator. Open the command prompt with "Run as administrator".

--reload fails on Windows

The service sgcProxy cannot be opened: <reason> means that the service is not installed, or that the account has no right to control it. The reload request was refused: <reason> usually means that the service is not running.

A reload did not change anything

An invalid file leaves the running configuration in place. The error is in the error log, and /status shows it in reloads.last_error with reloads.failed. Run --test on the file to see it.

The service does not start on Linux

install.sh prints config test failed and does not start the service when the configuration is invalid. Run the test as the service user and read the journal with journalctl -u sgcproxy. A path the proxy cannot write to is often outside the ReadWritePaths of the unit, see Installation on Linux.

A listen port is already in use

sgcProxy does not start and reports start failed: cannot listen on <address>:<port> (address <address>, port <port>): Address already in use. The process exits with code 1. The message goes to the error log and, since this version, also once to stderr, so it appears in the console and in journalctl -u sgcproxy. The usual cause is another program that listens on that port. On Linux run ss -ltnp 'sport = :<port>', on Windows run netstat -ano | findstr :<port>.

If nothing listens on the port and the start fails only now and then, the port is probably taken by an outgoing connection. On Linux a port inside the ephemeral range (net.ipv4.ip_local_port_range, 32768-60999 by default) can be used by an outgoing connection of another program or of sgcProxy itself. Listen on a port below 32768, or reserve the port with net.ipv4.ip_local_reserved_ports, for example sysctl -w net.ipv4.ip_local_reserved_ports=8443, and make it permanent with a file in /etc/sysctl.d/. On Windows the dynamic range is 49152-65535 by default (netsh int ipv4 show dynamicport tcp). Exclude a port from it with netsh int ipv4 add excludedportrange protocol=tcp startport=<port> numberofports=1 from an elevated prompt.

No admin listener

A port of global.admin.listen that cannot be bound is logged at error level, and the proxy runs without the admin listener. Pick another port.

HTTPS hosts get the wrong certificate after an ACME setup

Until the first certificate is issued, handshakes for that host get the default certificate of the listener or fail, and the error log says so at warn level. A failed order is retried after 1 hour, doubling up to 24 hours. /status shows the failures per certificate. Check that port 80 (HTTP-01) or port 443 (TLS-ALPN-01) of the names reaches sgcProxy.

Status codes from the proxy

StatusUsual cause
400A malformed request, or an upgrade request over HTTP/2.
403The WAF, an allow or deny list, or a client outside admin.allow. The WAF writes a warn line to the error log.
413The request body is larger than client_max_body_size.
429A rate limit zone, with Retry-After. The status can be changed with status in the zone.
502The upstream cannot be reached or sends an invalid answer, or every server is down.
504The upstream did not answer within read_timeout.