Skip to content

// Engineering Log

HTTPS and the web server in practice: Part 7 — Reference Nginx config for an HTTPS site and a verification checklist

Published on 2026-11-13 · Author:

// Fast route

This article belongs to the topic Security and protection.

HTTPS settings are scattered across a dozen topics: certificate and chain, TLS versions, redirects, HSTS, security headers, HTTP/2 and HTTP/3, caching, proxying to the application, WebSocket, timeouts. This article collects everything into a single config that you can use as a basis for a new site, and a checklist of commands to verify the result. The config was tested on Nginx 1.31 in Docker: nginx -t passes, and all checks from the checklist give the expected result.

Initial conditions: site example.ru, Let’s Encrypt certificate from certbot in /etc/letsencrypt/live/example.ru/, the application listens on 127.0.0.1:8080, built static files with a hash in the name are located in /var/www/example.ru/public/assets/. Nginx 1.25.1 or newer is required (directives http2 on and http3 on); official packages from nginx.org are built with HTTP/3 support.

File structure

/etc/nginx/
├── nginx.conf                  # from the package, do not change: includes conf.d/*.conf
├── conf.d/
│   ├── 00-common.conf          # common settings: log, compression, upstream
│   ├── 10-default.conf         # default server for unknown names
│   └── example.ru.conf         # the site
└── snippets/
    ├── ssl.conf                # TLS parameters
    ├── security-headers.conf   # security headers
    └── proxy.conf              # headers for proxying to the application

Snippets are included with the include directive. This not only reduces repetition, but also avoids the main add_header trap discussed below.

snippets/ssl.conf

nginx
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_timeout 1d;
ssl_session_cache shared:SSL:10m;
ssl_session_tickets off;

Mozilla’s intermediate profile: TLS 1.2 and 1.3; for TLS 1.2 only forward-secret AEAD ciphers. ssl_session_tickets off — session tickets without regular key rotation weaken forward secrecy; session resumption works via the ssl_session_cache. Why these ciphers — see the article “TLS versions, cipher suites, SNI, ALPN, ECH and mTLS”.

snippets/security-headers.conf

nginx
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
add_header X-Content-Type-Options "nosniff" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
add_header X-Frame-Options "DENY" always;
add_header Permissions-Policy "camera=(), microphone=(), geolocation=()" always;
add_header Content-Security-Policy-Report-Only "default-src 'self'; img-src 'self' data:; object-src 'none'; base-uri 'none'; frame-ancestors 'none'" always;
add_header Alt-Svc 'h3=":443"; ma=86400' always;
  • HSTS for one year including subdomains. If you have subdomains without HTTPS, remove includeSubDomains; on a new site start with max-age=300 and increase gradually (“Moving to HTTPS: redirects, HSTS, HTTPS-First”);
  • CSP in Report-Only mode: the browser reports violations to the console but does not block anything. Collect violations, adjust the policy for your scripts and trackers, then replace the header with Content-Security-Policy;
  • Alt-Svc announces HTTP/3 to the browser. It is placed here rather than in the server block so it won’t get lost inside a location with its own add_header;
  • always — headers are sent also in error responses.

The add_header trap. If there is at least one add_header in a location, all add_header directives from the server level stop working in that location. Therefore, in every location with its own add_header (below — static caching) the snippet is included again.

snippets/proxy.conf

nginx
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;
proxy_set_header X-Forwarded-Host  $host;

The application behind the proxy receives the real client IP and the scheme. Without X-Forwarded-Proto the application may assume it’s operating over HTTP and enter an infinite redirect loop to HTTPS.

conf.d/00-common.conf

nginx
server_tokens off;

map $http_upgrade $connection_upgrade {
    default upgrade;
    ''      close;
}

log_format main_timing '$remote_addr - [$time_local] "$request" $status $body_bytes_sent '
                       '"$http_referer" "$http_user_agent" '
                       'rt=$request_time urt=$upstream_response_time us=$upstream_status '
                       'proto=$server_protocol tls=$ssl_protocol';

gzip on;
gzip_comp_level 5;
gzip_min_length 1024;
gzip_proxied any;
gzip_vary on;
gzip_types text/css application/javascript application/json image/svg+xml text/plain text/xml application/xml;

upstream app {
    server 127.0.0.1:8080;
    keepalive 32;
    keepalive_timeout 4s;
}
  • server_tokens off — do not show the Nginx version;
  • log with timings: rt — total request time, urt — application response time, us — application status. From these you can immediately see where time is lost and who returned the error (“Errors 502, 504, 499 and 413 in Nginx”);
  • gzip for text types; gzip_vary on adds Vary: Accept-Encoding so caches don’t mix up compressed and uncompressed versions. Images and fonts like woff2 are already compressed — they are not listed;
  • upstream with keepalive: connections to the app are reused. keepalive_timeout 4s should be less than the app idle timeout (Node.js default is 5s), otherwise you will get occasional 502s.

conf.d/10-default.conf

nginx
# Requests with an unknown name and by IP: close the connection without revealing certificates
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;
}

Handles requests with unknown names and by IP address. Over HTTP Nginx closes the connection without a response (code 444); over HTTPS it rejects the handshake without revealing certificates (ssl_reject_handshake, Nginx 1.19.4+). This prevents Host header spoofing and IP-based scanning (“Attacks at the HTTP level”).

conf.d/example.ru.conf

nginx
# HTTP: only Let's Encrypt check and redirect to HTTPS
server {
    listen 80;
    listen [::]:80;
    server_name example.ru www.example.ru;

    location /.well-known/acme-challenge/ {
        root /var/www/letsencrypt;
    }
    location / {
        return 301 https://example.ru$request_uri;
    }
}

# www → main domain
server {
    listen 443 ssl;
    listen [::]:443 ssl;
    http2 on;
    server_name www.example.ru;

    ssl_certificate     /etc/letsencrypt/live/example.ru/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.ru/privkey.pem;
    include snippets/ssl.conf;

    return 301 https://example.ru$request_uri;
}

# Main site
server {
    listen 443 ssl;
    listen [::]:443 ssl;
    listen 443 quic reuseport;
    listen [::]:443 quic reuseport;
    http2 on;
    http3 on;
    server_name example.ru;

    ssl_certificate     /etc/letsencrypt/live/example.ru/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.ru/privkey.pem;
    include snippets/ssl.conf;
    include snippets/security-headers.conf;

    access_log /var/log/nginx/example.ru.access.log main_timing;
    error_log  /var/log/nginx/example.ru.error.log warn;

    client_max_body_size 20m;
    root /var/www/example.ru/public;

    # Static assets with a hash in the name — cache forever
    location /assets/ {
        include snippets/security-headers.conf;
        add_header Cache-Control "public, max-age=31536000, immutable" always;
        try_files $uri =404;
    }

    # Images and other static files without a hash
    location ~* \.(?:png|jpe?g|webp|avif|gif|svg|ico|woff2)$ {
        include snippets/security-headers.conf;
        add_header Cache-Control "public, max-age=86400" always;
        try_files $uri =404;
    }

    # WebSocket
    location /ws/ {
        proxy_pass http://127.0.0.1:8080;
        include snippets/proxy.conf;
        proxy_set_header Upgrade    $http_upgrade;
        proxy_set_header Connection $connection_upgrade;
        proxy_read_timeout 3600s;
    }

    # Application
    location / {
        try_files $uri @app;
    }
    location @app {
        proxy_pass http://app;
        include snippets/proxy.conf;
        proxy_set_header Connection "";   # keepalive to the application
        proxy_connect_timeout 5s;
        proxy_read_timeout    60s;
    }
}

What happens here:

  • port 80 — only Let’s Encrypt checks and a permanent redirect immediately to the final address https://example.ru preserving the path;
  • www — a separate block redirecting to the main domain; the certificate must include both names;
  • main site — HTTP/2 over TCP and HTTP/3 over QUIC on the same port 443. reuseport for QUIC is specified only in one server block per address;
  • static assets with a hash — cache for one year with immutable; other static files — for one day (“HTTP caching and CDN”);
  • WebSocket — proxied directly to the app, with Upgrade and Connection headers and a long read timeout;
  • everything else — first try the file on disk, if it does not exist then proxy to the application via an upstream with keepalive.

Installation

bash
sudo mkdir -p /etc/nginx/snippets /var/www/letsencrypt
# place the files in their locations, then:
sudo certbot certonly --webroot -w /var/www/letsencrypt \
  -d example.ru -d www.example.ru --deploy-hook 'systemctl reload nginx'
sudo nginx -t && sudo systemctl reload nginx
sudo ufw allow 80/tcp && sudo ufw allow 443/tcp && sudo ufw allow 443/udp

While the certificate is missing, the 443 blocks will prevent Nginx from starting. Issue the certificate after temporarily leaving only the block on port 80, or use certbot --nginx. UDP/443 is needed for HTTP/3.

Verification checklist

All commands run from your computer. Expected results are shown in comments.

bash
# 1. HTTP → HTTPS preserving the path
curl -s -o /dev/null -w '%{http_code} %{redirect_url}\n' 'http://example.ru/page?x=1'
# 301 https://example.ru/page?x=1

# 2. www → main domain
curl -s -o /dev/null -w '%{http_code} %{redirect_url}\n' https://www.example.ru/page
# 301 https://example.ru/page

# 3. unknown name over HTTP and HTTPS
curl -s -o /dev/null -w '%{http_code}\n' -H 'Host: evil.example' http://192.0.2.10/
# 000 (connection closed, code 444)
curl -sk -o /dev/null -w '%{http_code}\n' --resolve evil.example:443:192.0.2.10 https://evil.example/
# 000 (handshake rejected)

# 4. security headers, including in error responses
curl -sI https://example.ru/ | grep -iE '^(strict|x-content|referrer|x-frame|permissions|content-security|alt-svc)'
curl -sI https://example.ru/no-such-page | grep -ic '^strict-transport-security'
# 1

# 5. static cache
curl -sI https://example.ru/assets/app.1a2b.js | grep -i '^cache-control'
# cache-control: public, max-age=31536000, immutable

# 6. protocol versions
curl -s -o /dev/null -w '%{http_version}\n' https://example.ru/            # 2
curl -s -o /dev/null -w '%{http_version}\n' --http3-only https://example.ru/   # 3, if curl is built with HTTP/3

# 7. TLS: chain, version, cipher
openssl s_client -connect example.ru:443 -servername example.ru -brief </dev/null
# Protocol version: TLSv1.3 ... Verification: OK

# 8. full check of versions and ciphers
testssl.sh example.ru

Additionally:

  • SSL Labs (ssllabs.com/ssltest) — final rating A or A+ (A+ requires HSTS);
  • DevTools → Network, Protocol column — h2, after revisiting h3;
  • example.ru.access.log — requests have rt= and urt=, tls=TLSv1.3;
  • certbot renew --dry-run — renewal should succeed and --deploy-hook should reload Nginx.

An example of a proxy for an application with WebSocket and a protected admin area (Vaultwarden): Secrets and Zero Trust: Part 2 — Vaultwarden behind Caddy or Nginx and initial protection.

What to change for your needs

  • Site without an application (static): remove the upstream, location /ws/ and @app; in location / leave try_files $uri $uri/ =404;, and for HTML add Cache-Control: no-cache.
  • Uploading large files: increase client_max_body_size in the needed location, not for the whole site.
  • Long-running requests (reports, exports): create a separate location with an increased proxy_read_timeout.
  • Site behind a CDN or load balancer: configure set_real_ip_from for their addresses, otherwise logs and the application will see CDN addresses instead of visitors; decide where to set HSTS and headers — on the CDN or the origin, but not in both places.
  • API for other sites: CORS — by a list of origins using map (“What is CORS”).

// Similar task

If you are dealing with something similar

This article belongs to one of the main working topics. You can keep reading on the topic, go to the homepage to understand what I do, or open the service pages directly.

Article topic

Security and protection

SSL, hardening, access control, service protection, and secure configurations.

Typical tasks behind this topic

  • Set up SSL, certificates, and secure connections
  • Restrict access and close unnecessary entry points
  • Harden server and service configuration

// Next step

If you need help with this topic, not just another article, it is better to go straight to the service page. The homepage and topic collection stay available as secondary routes.

Open services

// Reviews

Related reviews

apande

apande

Configuring Nginx and OpenCart

2024-09-07 · ★ 5/5

A very powerful buyer
kireevk

kireevk

Diagnosing Nginx Proxy Manager in a Docker container and resolving the issue

2024-03-15 · ★ 5/5

Settled-in customer

// Contact

Need help?

Get in touch with me and I'll help solve the problem

I reply within one business day (03:00-13:00 GMT)

Or leave a request here:

Confirm that you are not a bot.

Write and get a quick reply