
A Self-Hosted LLM Behind HTTPS: Nginx Gateway, Bearer-Token Auth, and Let's Encrypt
A self-hosted model server like FreeToken is easy to reach from the same LAN it
runs on and easy to get wrong the moment you want to reach it from anywhere
else. Exposing the backend port directly to the internet trades convenience for
real risk: an unauthenticated /v1/* endpoint on a public IP lets anyone who
finds it burn GPU time, or use it as a free relay for their own traffic.
This article documents a gateway pattern that leaves the model server untouched and LAN-only. A dedicated Nginx host sits in front of it and handles TLS termination, a mandatory Bearer-token check, and basic rate limiting, all before a request reaches the inference process.
This is a hands-on infrastructure walkthrough, not an introduction to any of
its parts. It assumes you are already comfortable with basic Linux
administration (sudo, file permissions), editing Nginx config files, and
running commands over SSH. If any of that is new, treat the linked Nginx and
Certbot docs as prerequisite reading before working through the steps below.
The example uses placeholder values throughout: a fictitious domain
(llm-gateway.example.com), private LAN addresses from the documentation-reserved
192.0.2.0/24 and 198.51.100.0/24 ranges, and a placeholder API key. Substitute
your own domain, network addresses, and a freshly generated secret. Never reuse
the example token shown here.
Architecture at a glance
Public endpoint: https://llm-gateway.example.com/v1
Public IP: 203.0.113.10 (example, your router's WAN IP)
Nginx gateway: 192.0.2.51 (example, LAN host running Nginx)
FreeToken: 192.0.2.88:8000 (example, LAN host running the model)
Model: qwen3.6-35b-a3b
Context: 262144 tokens
View PlantUML source code
@startuml
skinparam componentStyle rectangle
actor "Internet client" as Client
node "Home router\n203.0.113.10 (public IP)" as Router {
component "Port forward\nWAN 443 -> 192.0.2.51:443" as PortForward
}
node "Nginx gateway\n192.0.2.51" as Gateway {
component "TLS termination\n(Let's Encrypt)" as TLS
component "Bearer API-key check" as Auth
component "Rate / connection limits" as Limits
}
node "FreeToken host\n192.0.2.88:8000" as Backend {
component "OpenAI-compatible /v1/*" as API
component "Qwen3.6-35B-A3B" as Model
}
Client --> Router : HTTPS\nAuthorization: Bearer <API_KEY>
Router --> Gateway : TCP 443 forwarded
Gateway --> TLS
TLS --> Auth
Auth --> Limits : only if authorized
Limits --> Backend : LAN HTTP\n(Authorization header stripped)
Backend --> API
API --> Model
Auth -[hidden]-> TLS
@enduml
Nginx accepts the external HTTPS traffic, terminates TLS, verifies the Bearer
API key before proxying, applies rate and connection limits, and only then
forwards the request to FreeToken over the LAN. The backend at
192.0.2.88:8000 should never be reachable directly from the internet. Only the
Nginx gateway is publicly exposed.
A dummy or missing API key is not authentication. Without this check, any request that reaches the gateway's
/v1/*path (including ones from strangers who find the domain through automated scanning) would fully consume GPU inference time. In this setup, any request to/v1/*without a correct, exact Bearer token gets401 Unauthorizedand never reaches FreeToken at all.
1. Network, DNS, and certificate
This setup requires a static public IP from your ISP. A DNS A record points at a fixed address, so if your ISP only hands out dynamic IPs, the record breaks every time it changes. In that case, use a dynamic DNS (DDNS) service instead of a plain A record, or ask your ISP for a static IP add-on.
Point a DNS A record at your public IP before doing anything else:
llm-gateway.example.com. A 203.0.113.10
On the home router, forward only the two ports the gateway actually needs:
WAN TCP 80 -> 192.0.2.51:80
WAN TCP 443 -> 192.0.2.51:443
Port 80 is required for Let's Encrypt's HTTP-01 issuance and renewal challenge.
Port 443 is what API clients use. Do not forward the backend's port (8000 in
this example) to the WAN under any circumstance.
On the Nginx host, confirm FreeToken is reachable over the LAN before configuring anything public-facing:
curl --fail-with-body -sS http://192.0.2.88:8000/v1/models
The response should be JSON containing data[0].id equal to qwen3.6-35b-a3b,
the exact name the server was started with via --served-model-name.
Install the required packages on the gateway host:
sudo apt update
sudo apt install -y nginx certbot python3-certbot-nginx
sudo systemctl enable --now nginx
Create a minimal HTTP-only virtual host first. Certbot needs a working, reachable server on port 80 before it can issue a certificate:
sudo tee /etc/nginx/sites-available/llm-gateway.example.com >/dev/null <<'NGINX'
server {
listen 80;
listen [::]:80;
server_name llm-gateway.example.com;
access_log /var/log/nginx/llm-gateway.example.com.access.log;
error_log /var/log/nginx/llm-gateway.example.com.error.log warn;
location / {
return 301 https://$host$request_uri;
}
}
NGINX
sudo ln -s /etc/nginx/sites-available/llm-gateway.example.com \
/etc/nginx/sites-enabled/llm-gateway.example.com
sudo nginx -t
sudo systemctl reload nginx
Before running Certbot, verify the domain resolves and responds from outside your own network, for example over a mobile data connection rather than Wi-Fi. If the home router doesn't support NAT loopback, testing from inside the LAN can produce a false positive or a false failure that has nothing to do with the actual public path.
curl -I http://llm-gateway.example.com
Issue the certificate:
sudo certbot --nginx -d llm-gateway.example.com
If the ISP uses CGNAT, blocks inbound port 80, or port forwarding simply isn't an option, use a DNS-01 challenge with your DNS provider instead.
2. Mandatory Bearer API key
2.1. What gets checked
Every client request must carry an exact header:
Authorization: Bearer <API_KEY>
For example:
Authorization: Bearer 4f6c1e9a2b7d0834f5c9a1e6b3d8072c9a4e1f6b8d3072ce9a1f4b6d803c2e97
Nginx reads the raw header value through the $http_authorization variable. A
map directive compares it against the exact string Bearer <API_KEY> and sets
a flag, $gateway_authorized, to 1 only on an exact match. Anything else (a
missing header, Basic ..., a truncated or mistyped token) leaves the flag at
0.
Inside location /v1/, Nginx then does:
if ($gateway_authorized = 0) {
add_header WWW-Authenticate 'Bearer realm="llm-gateway"' always;
return 401;
}
A request without the correct key is rejected immediately with 401 and never
reaches FreeToken's request queue or the GPU.
2.2. Generate the secret
On the gateway host:
sudo install -d -m 700 /etc/nginx/secrets
openssl rand -hex 32 | sudo tee /etc/nginx/secrets/gateway-api-key >/dev/null
sudo chmod 600 /etc/nginx/secrets/gateway-api-key
sudo cat /etc/nginx/secrets/gateway-api-key
Copy the value into a password manager immediately. Never commit it to Git, paste
it into chat, screenshot it, or leave it in a shared .env file.
2.3. Wire the check into http {}
Open the main config:
sudo nano /etc/nginx/nginx.conf
Add the block below inside http { ... }, ideally just before
include /etc/nginx/sites-enabled/*;. Replace <API_KEY> with the actual value
generated above:
# Authorization: Bearer <API_KEY> -> 1. Everything else -> 0.
map $http_authorization $gateway_authorized {
default 0;
"Bearer <API_KEY>" 1;
}
# Per-client-IP limits. Zone declarations are only valid inside http {}.
limit_req_zone $binary_remote_addr zone=gateway_per_ip:10m rate=2r/s;
limit_conn_zone $binary_remote_addr zone=gateway_conn_per_ip:10m;
With the example key above, the line would read:
"Bearer 4f6c1e9a2b7d0834f5c9a1e6b3d8072c9a4e1f6b8d3072ce9a1f4b6d803c2e97" 1;
Because the key now lives in this file, restrict who can read it:
sudo chown root:root /etc/nginx/nginx.conf
sudo chmod 640 /etc/nginx/nginx.conf
This is a single static key, reasonable for personal use or a small number of trusted devices. For per-user keys, rotation, quotas, or audit logging, a dedicated gateway (LiteLLM, for example) or an
auth_requestcall to a separate auth service is the better fit.
3. Nginx reverse-proxy configuration
Replace the site file entirely:
sudo nano /etc/nginx/sites-available/llm-gateway.example.com
server {
listen 80;
listen [::]:80;
server_name llm-gateway.example.com;
access_log /var/log/nginx/llm-gateway.example.com.access.log;
error_log /var/log/nginx/llm-gateway.example.com.error.log warn;
location / {
return 301 https://$host$request_uri;
}
}
server {
listen 443 ssl http2;
listen [::]:443 ssl http2;
server_name llm-gateway.example.com;
ssl_certificate /etc/letsencrypt/live/llm-gateway.example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/llm-gateway.example.com/privkey.pem;
include /etc/letsencrypt/options-ssl-nginx.conf;
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;
server_tokens off;
client_max_body_size 10m;
access_log /var/log/nginx/llm-gateway.example.com.access.log;
error_log /var/log/nginx/llm-gateway.example.com.error.log warn;
# No landing page, metrics, or arbitrary backend paths get published.
location = / {
return 404;
}
# Only the OpenAI-compatible API surface is exposed.
location /v1/ {
# Mandatory Bearer check before touching the upstream at all.
if ($gateway_authorized = 0) {
add_header WWW-Authenticate 'Bearer realm="llm-gateway"' always;
return 401;
}
# Guard against request bursts and too many long-lived streaming connections.
limit_req zone=gateway_per_ip burst=10 nodelay;
limit_req_status 429;
limit_conn gateway_conn_per_ip 4;
limit_conn_status 429;
# Without a trailing slash here, the /v1/... URI passes through unchanged.
proxy_pass http://192.0.2.88:8000;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
# The Bearer token was already verified by Nginx; don't forward it to the LAN backend.
proxy_set_header Authorization "";
# Required for OpenAI-style stream=true / server-sent events.
proxy_buffering off;
proxy_request_buffering off;
proxy_cache off;
add_header X-Accel-Buffering no always;
# Long generations and queued inference must not be cut off early.
proxy_connect_timeout 10s;
proxy_send_timeout 3600s;
proxy_read_timeout 3600s;
send_timeout 3600s;
}
# Anything outside /v1/ is not proxied to the backend.
location / {
return 404;
}
}
Apply it:
sudo nginx -t
sudo systemctl reload nginx
sudo systemctl status nginx --no-pager
If reload fails, roll back to the last working config and check:
sudo journalctl -u nginx -n 100 --no-pager
sudo tail -n 100 /var/log/nginx/llm-gateway.example.com.error.log
4. Verification, SDK usage, and operations
Set the key as an environment variable on the client machine first:
export GATEWAY_API_KEY='PASTE_YOUR_SECRET_HERE'
Auth checks
No key should return 401:
curl -i https://llm-gateway.example.com/v1/models
Wrong key should also return 401:
curl -i \
-H 'Authorization: Bearer wrong-key' \
https://llm-gateway.example.com/v1/models
Correct key should return 200 with the model list:
curl --fail-with-body -sS \
-H "Authorization: Bearer $GATEWAY_API_KEY" \
https://llm-gateway.example.com/v1/models
Chat completion
curl --fail-with-body -sS \
https://llm-gateway.example.com/v1/chat/completions \
-H 'Content-Type: application/json' \
-H "Authorization: Bearer $GATEWAY_API_KEY" \
-d '{
"model": "qwen3.6-35b-a3b",
"messages": [
{"role": "user", "content": "Reply with one word: is the gateway working?"}
],
"stream": false
}'
For streaming, change only two things: add -N --no-buffer so curl doesn't
buffer server-sent events, and set "stream": true in the body. The URL,
headers, and method all stay identical.
OpenAI Python SDK
import os
from openai import OpenAI
client = OpenAI(
base_url="https://llm-gateway.example.com/v1",
api_key=os.environ["GATEWAY_API_KEY"],
)
response = client.chat.completions.create(
model="qwen3.6-35b-a3b",
messages=[{"role": "user", "content": "Hello!"}],
)
print(response.choices[0].message.content)
The SDK builds the Authorization: Bearer <GATEWAY_API_KEY> header
automatically, so there's no manual header handling on the client side.
Operational notes
- Never store the API key in Git, documentation, shell history, shared chat, or application code.
- If the key is ever compromised, generate a new one, update the
mapblock, runsudo nginx -t && sudo systemctl reload nginx, then remove the old key from every client. rate=2r/s,burst=10, andlimit_conn ... 4are conservative starting points; tune them once you've observed real traffic. They cap raw HTTP load, not concurrency or token-budget limits, which still need to be enforced at the inference layer itself.- If you put this behind Cloudflare's proxy, Nginx will see Cloudflare's IP
rather than the real client IP by default. Until
real_ip_headerand Cloudflare's IP ranges are configured, either keep DNS-only mode or don't rely on IP-based rate limiting as a client identity signal. - Enable and test certificate renewal ahead of expiry:
sudo systemctl enable --now certbot.timer
sudo certbot renew --dry-run
- For live troubleshooting:
sudo tail -f \
/var/log/nginx/llm-gateway.example.com.access.log \
/var/log/nginx/llm-gateway.example.com.error.log
5. Deployment pitfalls worth knowing in advance
5.1. map_hash_bucket_size too small for a long API key
The default map_hash_bucket_size is 64. A 64-character hex API key embedded
in a map string key ("Bearer <64-hex-chars>" 1;) exceeds that, and Nginx
refuses to start:
nginx: [emerg] could not build map_hash, you should increase map_hash_bucket_size: 64
Fix it by adding this inside http { ... } in nginx.conf, before
include sites-enabled:
map_hash_bucket_size 128;
This applies to any
mapdirective with long string keys, not just this one. Check the length of keys in any othermapblocks you're running.
5.2. sudo tee breaks under non-interactive SSH automation
When automating config changes over SSH (Paramiko, Fabric, or similar tools that
run exec_command without a TTY), sudo tee file cannot prompt for a password.
The common workaround, echo 'content' | sudo tee file > /dev/null, doesn't work
either. tee consumes the piped content as its input, leaving nothing to answer
the password prompt.
The reliable pattern for writing root-owned files over a non-TTY SSH session:
- Write to a temp file as the logged-in user:
cat > /tmp/_tmp_file - Copy it into place as root:
sudo cp /tmp/_tmp_file /etc/nginx/file - Remove the temp file:
rm -f /tmp/_tmp_file
Alternatively, use echo 'password' | sudo -S bash -c 'command'.
5.3. apt --reinstall won't restore an edited config
If a config file has been modified, even reduced to zero bytes,
apt --reinstall nginx will not overwrite it. dpkg treats a changed file as
intentionally modified and leaves it alone. Recovering means writing the config
back by hand, matching the distribution's stock default.
5.4. Certbot depends on nginx.conf already being valid
The Certbot Nginx plugin runs nginx -t before attempting to issue anything, and
refuses to proceed if the test fails. An error like
nginx: [emerg] no "events" section looks like a DNS or port-forwarding problem
but actually means nginx.conf is empty or corrupted. Always confirm
sudo nginx -t passes before invoking Certbot.
5.5. Testing on localhost vs. the real domain
curl https://localhost/v1/models will fail certificate verification locally,
since the certificate was issued for llm-gateway.example.com, not localhost.
For local testing, either:
# Skip certificate verification.
curl -ks https://localhost/v1/models
# Or point the hostname at localhost via /etc/hosts.
echo "127.0.0.1 llm-gateway.example.com" | sudo tee -a /etc/hosts
curl -k https://llm-gateway.example.com/v1/models
-k/--insecureis needed here because the certificate is valid, but the hostname it was issued for doesn't matchlocalhost.
5.6. NOPASSWD sudoers syntax
A file like /etc/sudoers.d/deploy-nopasswd must contain exactly one line with
no embedded newline (a common mistake when generating the file from a script that
inserts a literal \n):
deploy ALL=(ALL) NOPASSWD: ALL
A malformed version with an embedded \n produces:
/etc/sudoers.d/deploy-nopasswd:1:10: syntax error
Putting it together
None of the individual steps above is hard: DNS, Certbot, and a reverse-proxy
location block are all standard Nginx work. Security here hangs on two
ordering decisions. The Bearer check has to run before proxy_pass, not after,
and the Authorization header has to be stripped before the request leaves the
gateway for the LAN. Get those two right, verify all three auth states (no key,
wrong key, correct key), and the rest is routine maintenance: rotate the key if
it leaks, watch the rate-limit thresholds under real traffic, and keep
certificate renewal on a timer.
Resources
- FreeToken: https://github.com/FlashML-org/FreeToken
- Nginx
mapmodule: https://nginx.org/en/docs/http/ngx_http_map_module.html - Certbot: https://certbot.eff.org/
Published on 9/3/2026