Behind a reverse proxy
A reverse proxy in front of nvs serve handles HTTPS, compression, static files and rate limits.
nvs serve does not do these jobs. This page shows a configuration for nginx and for Caddy, first
for production and then for development.
HTTP/2 and HTTP/3
Section titled “HTTP/2 and HTTP/3”nvs serve speaks HTTP/1.1 only. The browser connects to the proxy with HTTP/2 or HTTP/3. The proxy
then sends each request to Novis with HTTP/1.1.
Your visitors still get the speed of HTTP/2 and HTTP/3. These protocols are faster on the network between the browser and the proxy, for example on a slow mobile connection. The proxy and Novis run on the same machine. The proxy keeps a few connections to Novis open, and it uses them again for every request.
Production and development
Section titled “Production and development”| Production | Development | |
|---|---|---|
| Novis listens on | a Unix socket, or 127.0.0.1:8000 on Windows |
127.0.0.1:8000 |
| Static files | the proxy serves them | Novis serves them |
| HTTPS | a real certificate, for example from Let’s Encrypt | a local certificate, or plain HTTP |
| Rate limit | yes | no |
In development you do not need a proxy. nvs serve runs your program and serves its files. Use a
proxy in development only to test HTTPS, HTTP/2 or the proxy configuration itself.
Listen where only the proxy can connect
Section titled “Listen where only the proxy can connect”Let the server listen on the loopback address, so only programs on the same machine can reach it:
[server]listen = ["127.0.0.1:8000"]On Linux, a Unix socket is better. The operating system then checks who may connect:
[server]listen = ["/run/shop/nvs.sock"]socket_mode = "0660"With 0660, the account of the server and the members of its group may connect. Add the account of
the proxy to that group. On Debian and Ubuntu, nginx runs as www-data. Caddy runs as caddy:
usermod -aG shop www-data # for nginxusermod -aG shop caddy # for CaddyRestart the proxy after this change, so it runs with the new group.
The folder /run/shop must exist before the server starts. Linux empties /run at every boot.
nvs service sets this up for you. systemd then creates the
folder at every start of the service, and deletes it when the service stops. The folder belongs to
the account of the service. Members of its group can open it, so the proxy can reach the socket.
nvs service reads listen when you install the service. If you change listen later, uninstall
the service and install it again. Put the socket in a folder of its own, such as /run/shop, and
not directly in /run.
Tell Novis which proxy to trust
Section titled “Tell Novis which proxy to trust”By default, Novis reads no forwarding header. Core\Request::clientIp() then returns the address of
the proxy, and Core\Request::scheme() returns http.
List the address of your proxy in trusted_proxies. You can write one address or a block of
addresses:
[server]listen = ["127.0.0.1:8000"]trusted_proxies = ["127.0.0.1"]Now clientIp() returns the address of the client from X-Forwarded-For. scheme() returns
https when the proxy sent X-Forwarded-Proto: https. A client cannot send a false address,
because Novis reads only the address that your proxy added.
A Unix socket needs no entry of its own, but the list must not be empty. When the list has an entry, Novis trusts every connection on the socket, because only accounts that may open the socket can connect. With an empty list, Novis reads no forwarding header on the socket either:
[server]listen = ["/run/shop/nvs.sock"]socket_mode = "0660"trusted_proxies = ["127.0.0.1"]Without this, scheme() returns http for every request. A browser sends Origin: https://shop.example.com with each form and each WebSocket, and Novis compares it with http. The
two do not match, so every form and every WebSocket gets the status 403.
Novis reads the client address from X-Forwarded-For only. It does not read X-Real-IP or
Forwarded. The configurations below send X-Forwarded-For.
Production configuration
Section titled “Production configuration”In production, Novis runs your entry file for every request. It does not serve static files. The
proxy serves the files in your public folder, and it sends every other request to Novis.
This configuration needs nginx 1.25.1 or newer. For HTTP/3, the output of nginx -V must contain
--with-http_v3_module. The packages from nginx.org have it.
Save the configuration as /etc/nginx/conf.d/shop.conf. nginx reads the files in this folder
inside its http block.
# Rate limit: 20 requests per second for each client address.limit_req_zone $binary_remote_addr zone=shop:10m rate=20r/s;
# Login limit: 10 login attempts per minute for each client address.# Only a POST request has a key, so opening the login page does not count.map $request_method $shop_login_key { POST $binary_remote_addr; default '';}limit_req_zone $shop_login_key zone=shop_login:10m rate=10r/m;
# Connection limit: counts the open connections of each client address.limit_conn_zone $binary_remote_addr zone=shop_conn:10m;
# A WebSocket request sends "Connection: upgrade" to Novis.# Every other request sends an empty value, so the connection stays open.map $http_upgrade $connection_upgrade { default upgrade; '' '';}
upstream shop { server unix:/run/shop/nvs.sock; # On TCP: server 127.0.0.1:8000;
# Keep up to 16 unused connections to Novis open for each nginx worker. keepalive 16; # Shorter than the 75 seconds after which Novis closes an unused connection. keepalive_timeout 60s;}
# A request for an unknown host name, or for the IP address of the server, gets no answer.server { listen 80 default_server; listen [::]:80 default_server; listen 443 ssl default_server; listen [::]:443 ssl default_server; ssl_reject_handshake on; return 444;}
# Plain HTTP only redirects to HTTPS.server { listen 80; listen [::]:80; server_name shop.example.com; return 301 https://$host$request_uri;}
server { listen 443 ssl; listen [::]:443 ssl; # HTTP/3 uses UDP port 443. listen 443 quic reuseport; listen [::]:443 quic reuseport; http2 on; server_name shop.example.com; server_tokens off;
ssl_certificate /etc/letsencrypt/live/shop.example.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/shop.example.com/privkey.pem; ssl_protocols TLSv1.2 TLSv1.3; ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305; ssl_prefer_server_ciphers off; ssl_session_cache shared:SSL:10m; ssl_session_timeout 1d; ssl_session_tickets off;
# The same limit as `upload_total` in nvs.toml. client_max_body_size 256m; # The same limits as `header_timeout` and `body_idle_timeout` in nvs.toml. client_header_timeout 10s; client_body_timeout 30s; # The same limit as `write_idle_timeout` in nvs.toml. send_timeout 30s; # A request line or a header line may have at most 8 KB. large_client_header_buffers 4 8k;
limit_req zone=shop burst=100 nodelay; limit_req_status 429; limit_conn shop_conn 50; limit_conn_status 429;
gzip on; gzip_vary on; gzip_types text/css text/plain application/javascript application/json image/svg+xml;
proxy_http_version 1.1; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $remote_addr; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection $connection_upgrade; # A WebSocket may be quiet for 5 minutes before Novis closes it. proxy_read_timeout 5m;
add_header Alt-Svc 'h3=":443"; ma=86400' always;
root /srv/shop/public;
# A file in the public folder is sent by nginx. Every other path goes to Novis. location / { try_files $uri @novis; add_header X-Content-Type-Options nosniff always; add_header Alt-Svc 'h3=":443"; ma=86400' always; }
# .nvs files and hidden files are never sent as files. location ~ (\.nvs$|/\.) { proxy_pass http://shop; }
# The login form has both rate limits. Write the path of your own login form. location = /login { limit_req zone=shop burst=100 nodelay; limit_req zone=shop_login burst=5 nodelay; proxy_pass http://shop; }
location @novis { proxy_pass http://shop; }}What the important lines do:
keepalive 16,proxy_http_version 1.1and theConnectionheader keep the connections to Novis open. Without all three, nginx opens a new connection for every request.keepalive_timeout 60sis shorter than thekeepalive_timeoutof Novis, which is 75 seconds. So nginx closes an unused connection first, and never sends a request on a closed connection.- Keep the line
proxy_set_header Host $host;. Without it, nginx sends the address fromproxy_passas the host. Novis chooses a mount by the host of the request. A mount with ahostsetting then gets no requests, and the mounts without ahostget them all. X-Forwarded-For $remote_addrreplaces any value the client sent with the address that nginx sees.- The location
(\.nvs$|/\.)sends.nvsfiles and hidden files to Novis. A hidden file has a name that starts with a dot, such as.env. Novis runs your entry file for these paths. - nginx allows request bodies up to 1 MB by default.
client_max_body_sizeraises this limit. Set it to the same size asupload_totalin yournvs.toml. - The first
serverblock is the default server. It gets every request whose host name is notshop.example.com.return 444closes the connection with no answer, andssl_reject_handshake onstops an HTTPS connection before it starts. So a scanner that only knows the IP address of your server never reaches Novis. - A
locationwith its ownlimit_reqlines uses only those lines. So the location= /loginrepeats the general limit next to the login limit. - Novis adds the security headers to its own responses,
Strict-Transport-Securitytoo. Do not add them again in nginx, or the browser gets them twice. nginx addsX-Content-Type-Optionsonly to the static files that it sends. - Write
reuseportin oneserverblock only. nginx does not start when two blocks use it for the same address and port. - Event streams need no setting. Novis sends
X-Accel-Buffering: nowith them, so nginx sends each event immediately.
Save this as /etc/caddy/Caddyfile:
{ servers { timeouts { # The same limit as `header_timeout` in nvs.toml. read_header 10s } }}
shop.example.com { root * /srv/shop/public encode zstd gzip
request_body { # The same limit as `upload_total` in nvs.toml. max_size 256MB }
# This block needs the plugin caddy-ratelimit. Caddy returns 429 above a limit. rate_limit { # Rate limit: 100 requests in 5 seconds for each client address. zone shop { key {remote_host} events 100 window 5s } # Login limit: 10 login attempts per minute for each client address. # Write the path of your own login form. zone shop_login { match { method POST path /login } key {remote_host} events 10 window 1m } }
# A file in the public folder that is not a .nvs file and not a hidden file. @static { file not path *.nvs not path_regexp /\. }
handle @static { header X-Content-Type-Options nosniff file_server }
handle { reverse_proxy unix//run/shop/nvs.sock { transport http { # Shorter than the 75 seconds after which Novis closes an unused connection. keepalive 60s } } }}On TCP, write reverse_proxy 127.0.0.1:8000 in place of the socket.
What the important lines do:
- Caddy gets the certificate from Let’s Encrypt and renews it. It redirects HTTP to HTTPS. It speaks HTTP/1.1, HTTP/2 and HTTP/3 without any setting. Open TCP ports 80 and 443 and UDP port 443.
- Caddy sends the
Hostof the request to Novis unchanged. It setsX-Forwarded-ForandX-Forwarded-Proto, and it replaces anyX-Forwarded-Forthat the client sent. - Caddy keeps connections to Novis open for 2 minutes by default.
keepalive 60sis shorter than the 75 seconds of Novis. So Caddy closes an unused connection first, and never sends a request on a closed connection. @staticmatches a file that exists in the public folder..nvsfiles and hidden files go to Novis. A hidden file has a name that starts with a dot, such as.env.read_header 10sgives a client 10 seconds to send the request headers. Caddy allows 1 minute by default.- Novis adds the security headers to its own responses,
Strict-Transport-Securitytoo. Do not add them again in Caddy. Caddy addsX-Content-Type-Optionsonly to the static files that it sends. rate_limitis not part of the normal Caddy download. Caddy does not start with this block until you build it with the plugin:xcaddy build --with github.com/mholt/caddy-ratelimit. Without the plugin, delete the block and set a rate limit in your firewall.- Caddy sends only requests for the host names in the Caddyfile to Novis. A request for another name, or for the IP address of the server, never reaches Novis.
- WebSockets and event streams need no setting.
What the proxy protects against
Section titled “What the proxy protects against”Novis does not limit requests for each client address. The proxy does this job. This table shows the common attacks, and the setting in each configuration above that stops them:
| Attack | nginx | Caddy |
|---|---|---|
| Many requests from one address | limit_req zone=shop |
the zone shop |
| Guessing passwords on the login form | limit_req zone=shop_login |
the zone shop_login |
| Many open connections from one address | limit_conn |
a limit in your firewall |
| Headers sent very slowly, to keep connections open | client_header_timeout |
read_header |
| A body sent very slowly, or a response read very slowly | client_body_timeout and send_timeout |
body_idle_timeout and write_idle_timeout in Novis |
| Very large headers | large_client_header_buffers |
16 KB, the default of Caddy |
| A very large body | client_max_body_size |
max_size |
| Requests for the IP address of the server, or for another host name | the default server | only the names in the Caddyfile |
Reading .env or the code of a .nvs file |
the location (\.nvs$|/\.) |
@static |
The numbers in the configurations are starting values. Choose them for your own traffic:
- Many people can share one address, for example in an office or on a mobile network. Choose limits that such a group stays under.
- In nginx,
limit_conncounts each request of an HTTP/2 or HTTP/3 connection as one connection. So 50 is also the most requests that one address can run at the same time. - The proxy counts by client address only. An attacker with many addresses can try many passwords
for one account. Limit the attempts for each account in your program with
Core\RateLimit::consume. - When a CDN is in front of the proxy, every request comes from an address of the CDN. Set the limits for each client in the CDN, and keep only the size limits and timeouts in the proxy.
Novis also protects itself. When more than max_in_flight requests run, the next ones get 503.
Every wait has a time limit. Read
Limits and logs.
Development configuration
Section titled “Development configuration”In development, Novis serves your static files itself. The proxy sends every request to Novis.
Set these values in the nvs.toml of your project:
[mode]default = "development"
[server]listen = ["127.0.0.1:8000"]trusted_proxies = ["127.0.0.1"]
[http.headers]hsts = falseNovis sends Strict-Transport-Security when the proxy reports HTTPS. A browser remembers this header
for a year. It may then open every port of localhost with HTTPS only. hsts = false turns the
header off.
In development, Novis checks the Host header of every request from this machine. Both
configurations below send localhost, which is always allowed. If your proxy uses another host
name, such as app.test, add it to the [server] block:
[server]development_hosts = ["app.test"]Without this entry, each request gets 421. The response says which host to add.
This configuration uses plain HTTP on port 8080. Open http://localhost:8080.
map $http_upgrade $connection_upgrade { default upgrade; '' '';}
server { listen 127.0.0.1:8080; server_name localhost; client_max_body_size 256m;
location / { proxy_pass http://127.0.0.1:8000; proxy_http_version 1.1; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $remote_addr; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection $connection_upgrade; proxy_read_timeout 5m; }}This configuration uses HTTPS with a local certificate on port 8443. Open https://localhost:8443.
localhost:8443 { reverse_proxy 127.0.0.1:8000}Caddy creates a certificate for localhost from its own local certificate authority. The first time,
Caddy adds this authority to your computer, so the browser accepts the certificate. You may need to
enter your password. caddy trust does the same step on its own.
A health check for the proxy
Section titled “A health check for the proxy”A load balancer can check whether the server is running. Set health_path:
[server]health_path = "/healthz"The path returns 200 while the server accepts requests. It returns 503 while the server stops,
so the load balancer sends new requests to another server. It does not run your program.
Do and don’t
Section titled “Do and don’t”- Do let
nvs servelisten on127.0.0.1or a Unix socket, never on a public address. - Do keep the connections to Novis open. In nginx, this needs
keepalivein theupstreamblock andproxy_http_version 1.1. - Do set
trusted_proxiesto the exact address of your proxy. - Do let the proxy serve the static files in production, and never send a
.nvsfile as a file. - Do set a rate limit in the proxy, and a stricter one for the login form.
- Do let a default server close the requests for unknown host names.
- Don’t list a whole network in
trusted_proxieswhen one address is enough. - Don’t add the security headers of Novis again in the proxy.
Read more in Reference: the server block.
