English
Nginx and HTTPS
Step 1. Why a reverse proxy
Why. Kestrel, the web server inside ASP.NET Core, is fast and could face the internet itself. Chatex still puts Nginx in front of it, as most deployments do, because the front door has jobs that do not belong in the application:
- TLS: certificates, their renewal and the encryption settings are handled in one place, by a tool made for it;
- static files: the Angular build is a folder of files; Nginx serves them from disk with compression and caching, without waking up .NET;
- one origin: the browser sees one address.
/is the Angular app,/apiand/hubsgo to the API. No CORS is needed, and theSecure, same-site refresh cookie just works; - protection: request size limits, timeouts and headers for every response, also for the static files.
A reverse proxy receives the request from the browser and forwards it to the real server — here Kestrel on 127.0.0.1:5000 — on the browser's behalf (Fig. 23.3). Caddy or Traefik would do the same with less configuration and built-in certificates; Nginx is the most widespread, its configuration is explicit, and Ubuntu packages it with a certbot plugin.
Fig. 23.3. What Nginx does with each path
Step 2. Security headers
Why. A few response headers make browsers enforce rules that protect the users of the site even if our code has a bug. They cost one line each, so every response should carry them — the HTML, the scripts and the API answers alike. Chatex keeps them in a small snippet that the site includes.
Do. On your computer, create the folder Deploy/nginx and the snippet:
nginx
# Security headers for the Chatex site, included by chatex.conf at server level and again in every location that
# sets its own add_header (Nginx drops inherited add_header directives in such locations).
# Install: cp Deploy/nginx/chatex-security-headers.conf /etc/nginx/snippets/
#
# CSP: scripts only from this origin (the theme script is the file theme-init.js, not inline); inline styles are
# allowed because Angular injects component styles as <style> elements; images may be blob: URLs (avatars and
# attachments fetched with the bearer token) or data: URLs; 'self' in connect-src also covers the same-origin
# wss:// connection of SignalR.
add_header Strict-Transport-Security "max-age=31536000" always;
add_header Content-Security-Policy "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' blob: data:; font-src 'self'; connect-src 'self'; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-Frame-Options "DENY" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
add_header Permissions-Policy "camera=(), microphone=(), geolocation=(), payment=(), usb=()" always;Table 23.3 shows what each header does.
Table 23.3. Security headers of Chatex
| Header | Effect | Protects against |
|---|---|---|
Strict-Transport-Security: max-age=31536000 | the browser uses only HTTPS for this site for one year, even if a link says http:// | downgrade to plain HTTP on a hostile network |
Content-Security-Policy | the browser loads and runs only what the policy allows (below) | injected scripts (cross-site scripting), data theft |
X-Content-Type-Options: nosniff | the browser trusts the declared content type and never guesses | a text file executed as a script |
X-Frame-Options: DENY | the site may not be shown inside a frame | clickjacking: a hidden Chatex under a fake button |
Referrer-Policy: strict-origin-when-cross-origin | other sites see only https://<your domain>, not the full address | leaking chat ids in URLs |
Permissions-Policy | camera, microphone, location, payment and USB are switched off | misuse of device features by injected code |
The Content Security Policy deserves a closer look, because it is the strongest protection against cross-site scripting:
default-src 'self'— by default, everything only from our own origin;script-src 'self'— scripts only from files of our origin; inline<script>blocks andevalare refused. This is why the client applies the saved theme before Angular starts with the filetheme-init.js, not with an inline script. Even if an attacker managed to put a script tag into a message, the browser would not run it;style-src 'self' 'unsafe-inline'— Angular adds component styles as<style>elements, which needs inline styles;img-src 'self' blob: data:— avatars and images are fetched with the bearer token and shown asblob:URLs (BlobUrlService, topic 18);connect-src 'self'—fetchand WebSocket connections only to our origin; this also coverswss://of SignalR on the same host;object-src 'none',base-uri 'self',form-action 'self',frame-ancestors 'none'— no plug-ins, no foreign<base>element, forms post only to us, and nobody may frame us (the modern form ofX-Frame-Options).
always at the end of each line adds the header to error responses too (4xx, 5xx); without it Nginx would add it only to successful ones.
Step 3. The site
Do. Create the site configuration next to the snippet:
nginx
# Chatex site: the Angular app from disk, /api, /hubs and /health proxied to Kestrel.
# Install: cp Deploy/nginx/chatex.conf /etc/nginx/sites-available/chatex
# cp Deploy/nginx/chatex-security-headers.conf /etc/nginx/snippets/
# ln -s /etc/nginx/sites-available/chatex /etc/nginx/sites-enabled/chatex
# nginx -t && systemctl reload nginx (server_name is chatex.mvano.com; change it for another domain)
# certbot --nginx -d chatex.mvano.com (adds the TLS server block and the redirect)
upstream chatex_api {
server 127.0.0.1:5000;
keepalive 16;
}
# WebSocket upgrade for SignalR; plain keep-alive for everything else.
map $http_upgrade $chatex_connection {
default upgrade;
'' '';
}
server {
listen 80;
listen [::]:80;
server_name chatex.mvano.com;
root /opt/chatex/current/web;
index index.html;
# Attachments are limited to 20 MB by default (Attachments:MaxBytes); leave room for the form.
client_max_body_size 25m;
include snippets/chatex-security-headers.conf;
# Text responses from disk and from the API (index.html is always compressed).
gzip on;
gzip_vary on;
gzip_proxied any;
gzip_comp_level 5;
gzip_min_length 1024;
gzip_types text/css text/plain application/javascript application/json application/problem+json image/svg+xml;
location ^~ /api/ {
proxy_pass http://chatex_api;
proxy_http_version 1.1;
proxy_set_header Connection '';
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_request_buffering off;
}
location ^~ /hubs/ {
proxy_pass http://chatex_api;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $chatex_connection;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_read_timeout 1h;
proxy_send_timeout 1h;
proxy_buffering off;
}
# The API only answers the hosts in AllowedHosts, so pass the real Host on here too.
location = /health {
proxy_pass http://chatex_api;
proxy_http_version 1.1;
proxy_set_header Connection '';
proxy_set_header Host $host;
access_log off;
}
# Hashed build output (outputHashing: all) never changes under the same name: main-IWEIRFGV.js, media/...
location ~* "-[a-z0-9_-]{8}\.(?:js|css)$" {
include snippets/chatex-security-headers.conf;
add_header Cache-Control "public, max-age=31536000, immutable";
try_files $uri =404;
}
location ^~ /media/ {
include snippets/chatex-security-headers.conf;
add_header Cache-Control "public, max-age=31536000, immutable";
try_files $uri =404;
}
# Everything else (index.html, SPA routes, favicons, site.webmanifest, theme-init.js) is revalidated on every load.
location / {
include snippets/chatex-security-headers.conf;
add_header Cache-Control "no-cache";
try_files $uri $uri/ /index.html;
}
}Replace chatex.mvano.com in server_name with your domain: Nginx answers for this name, and certbot looks for it in Step 5.
The upstream and the WebSocket map
upstream chatex_apinames the API:127.0.0.1:5000, the address ofASPNETCORE_URLSin the unit file.keepalive 16keeps up to 16 idle connections to Kestrel open, so not every request pays for a new TCP connection.map $http_upgrade $chatex_connectioncomputes theConnectionheader for the hub: if the browser sentUpgrade: websocket, the value isupgrade; if theUpgradeheader is empty, the value is empty. A WebSocket starts as an HTTP request that asks to "upgrade" the connection; a proxy must forward this request explicitly, becauseUpgradeandConnectionare hop-by-hop headers that a proxy normally drops.
The server block
listen 80,listen [::]:80— plain HTTP on IPv4 and IPv6. Certbot adds HTTPS in Step 5.root /opt/chatex/current/web— the files of the Angular build of the active release, through thecurrentlink. Switching the link switches the front end and the API together.client_max_body_size 25m— the largest request body Nginx accepts (default: 1 MB). Attachments may be 20 MB (Attachments:MaxBytes); the rest is room for the multipart form. Larger bodies are refused by Nginx with413before they reach the API.include snippets/chatex-security-headers.conf— the headers of Step 2 for every response of this server.gzip …— compresses text responses of at least 1 KB, from disk and, withgzip_proxied any, from the API.index.htmlis always compressed;gzip_typesadds CSS, JavaScript, JSON, problem details and SVG. The JavaScript of Chatex shrinks to about a fifth.
/api/, /hubs/ and /health
location ^~ /api/— every path that starts with/api/goes to the upstream.^~means "if this prefix matches, do not try the regular expressions below", so/api/…-abcdefgh.jscould never be mistaken for a cached file.proxy_http_version 1.1and an emptyConnectionheader enable the keep-alive connections of the upstream.Host $hostpasses the original host name. The API checks it againstAllowedHosts.X-Forwarded-ForandX-Forwarded-Prototell the API the real client address and that the browser used HTTPS.UseForwardedHeadersof topic 13 applies them; it trusts these headers only from a proxy on the loopback address, which Nginx is. Without them, the rate limiter would see every user as127.0.0.1and throttle them all together.proxy_request_buffering offstreams uploads straight to the API instead of storing them in a temporary file first.
location ^~ /hubs/— the SignalR hub: the same proxy settings plusUpgradeand the computedConnectionheader for WebSockets;proxy_read_timeout 1handproxy_send_timeout 1h, because a realtime connection may be quiet for a long time (the default of 60 seconds would cut it);proxy_buffering off, so every event reaches the browser at once.location = /health— exactly this path, for the smoke test of topic 24 and for monitoring;access_log offkeeps the frequent probes out of the log.
Caching and the single-page application
location ~* "-[a-z0-9_-]{8}\.(?:js|css)$"— the hashed files of the build, likemain-IWEIRFGV.js: the name changes whenever the content changes, so browsers may keep them for a year (immutable: not even revalidated). The same for/media/, where the build puts fonts and images with hashed names.location /— everything else, above allindex.html, withCache-Control: no-cache: the browser must ask on every load whether it has changed, so a new release is picked up at once.try_files $uri $uri/ /index.htmlserves an existing file, otherwiseindex.html— this is the fallback for client-side routes like/chats/…, which exist only in the Angular router.
add_header is not inherited
A location that has an add_header of its own loses all add_header directives of the server level. The three locations with Cache-Control would therefore send no security headers at all — unless they include the snippet again, which is exactly what they do. The proxy locations have no add_header and inherit the headers of the server.
Step 4. Installing the site
Do. Commit both files with your domain in server_name, and push them:
powershell
git add Deploypowershell
git commit -m "Add the Nginx site and the security headers"powershell
git pushOn the server:
bash
git pullbash
cp Deploy/nginx/chatex-security-headers.conf /etc/nginx/snippets/bash
cp Deploy/nginx/chatex.conf /etc/nginx/sites-available/chatex && ln -s /etc/nginx/sites-available/chatex /etc/nginx/sites-enabled/ && rm -f /etc/nginx/sites-enabled/defaultsites-availableholds site configurations; a symbolic link insites-enabledswitches one on. The main/etc/nginx/nginx.confof the package includes everything insites-enabled.rm -f …/defaultswitches off the welcome page of the package. Chatex is now the only site, so it also answers requests for the bare IP address.
Test the configuration and load it without interrupting connections:
bash
nginx -t && systemctl reload nginxCheck
nginx -t prints:
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successfulNow ask the site for its health over the internet, from your computer:
powershell
curl.exe -i http://<your domain>/healthThe answer is HTTP/1.1 502 Bad Gateway with the security headers: Nginx works, and the API behind it does not run yet. http://<your domain>/ answers 500 Internal Server Error for the same reason — there is no current/web/index.html yet, and /var/log/nginx/error.log explains it with rewrite or internal redirection cycle while internally redirecting to "/index.html". Both turn into real answers with the first release in topic 24.
Step 5. A certificate with certbot
Why. HTTPS encrypts the traffic and proves to the browser that it talks to the real server. Chatex cannot work without it: the refresh cookie is Secure and is never sent over plain HTTP, and the HSTS header is ignored on HTTP. Let's Encrypt issues free certificates, valid for 90 days, to anybody who can prove control of a domain. certbot automates the proof, the installation into Nginx and the renewal.
Do. The DNS record of the first chapter must point at the server by now (check with nslookup). Then:
bash
certbot --nginx -d <your domain>On the first run certbot asks for an e-mail address for expiry warnings and for your agreement to the terms of service. Then it
- asks Let's Encrypt for a certificate; Let's Encrypt sends a random token, certbot makes Nginx serve it under
http://<your domain>/.well-known/acme-challenge/…, and Let's Encrypt fetches it — proof that the domain points at this server (the HTTP-01 challenge, which is why port 80 must be open); - stores the certificate and its key under
/etc/letsencrypt/live/<your domain>/; - edits
/etc/nginx/sites-available/chatex: the server block now listens on 443 withssland the certificate, and a new small server block on port 80 answers every request with a redirect tohttps://. Each added line ends with# managed by Certbot; - reloads Nginx.
It ends with Successfully deployed certificate for <your domain> and Congratulations! You have successfully enabled HTTPS on https://<your domain>.
Check
From your computer:
powershell
curl.exe -I http://<your domain>/The answer is HTTP/1.1 301 Moved Permanently with Location: https://<your domain>/.
powershell
curl.exe -i https://<your domain>/healthThe answer is still 502 Bad Gateway — but now over HTTPS, with a certificate your computer trusts, and with Strict-Transport-Security among the headers. In the browser, https://<your domain>/ shows the lock icon (and an error page until the first release). On the server, the renewal is scheduled:
bash
systemctl status certbot.timer● certbot.timer - Run certbot twice daily
Loaded: loaded (/usr/lib/systemd/system/certbot.timer; enabled; preset: enabled)
Active: active (waiting) since …Test the renewal without changing anything:
bash
certbot renew --dry-runIt ends with Congratulations, all simulated renewals succeeded.
The installed file now differs from the repository
After certbot, /etc/nginx/sites-available/chatex contains the TLS lines and Deploy/nginx/chatex.conf does not, on purpose: the certificate paths belong to this server. If you change the site in the repository later and copy it again, the TLS lines are gone. Run nginx -t && systemctl reload nginx && certbot --nginx -d <your domain> again afterwards — certbot offers to reinstall the existing certificate.
The server is ready. Every part of Fig. 23.1 is installed except the application itself.