Last updated: 28 October 2026. Sources are listed at the end.
A secure Nginx configuration is mostly a short list of settings that the default install leaves out. Ubuntu’s package works out of the box, so it is easy to ship it as is. However, the defaults print the version number, send no security headers and put no limit on how fast one client can hit your login page.
This guide is for sysadmins and developers who run Nginx 1.24 on Ubuntu 24.04 LTS, either as a web server or as a reverse proxy in front of an app. We built every config below in a lab, validated it with nginx -t, started it and tested it with curl and openssl. You will see the real output, including one mistake that 1.24 rejects.
The short answer
- Turn off
server_tokens, allow only TLS 1.2 and 1.3, and redirect all HTTP traffic to HTTPS. - Send HSTS,
X-Content-Type-Options,X-Frame-Options,Referrer-Policy,Permissions-PolicyandCross-Origin-Opener-Policywith thealwaysflag. - Start Content-Security-Policy in Report-Only mode, then enforce it once the reports are clean.
- Keep headers in one include file, because an
add_headerinside a location removes every server-level header. - Rate limit login and API paths with
limit_reqandlimit_conn, and set a body size and short timeouts. - Block dotfiles such as
.envand.git, keepautoindexoff, and keep the Nginx package patched.
What a secure Nginx configuration covers
There are four layers. First, the transport layer: TLS versions, ciphers and the redirect from port 80. Second, the response headers that tell browsers how to treat your pages. Third, the limits on request rate, request size and slow clients. Finally, the things you never want served at all, such as hidden files and directory listings.
You still need patching and a secure application. These settings remove the easy wins that scanners look for on every public IP.
The test setup
We used Ubuntu 24.04.5 with the stock package nginx 1.24.0-2ubuntu7.19 and OpenSSL 3.0.13. We did not touch the system Nginx service. Instead, the lab ran from its own config under /tmp/secure-nginx/ with its own pid file, logs and temp paths. It listened on 127.0.0.1 ports 9080 and 9443, because 8443 was already in use in our container.
Step 1: Create a self-signed test certificate
This creates an ECDSA P-256 certificate for testing only. For a real site, use a certificate from a CA, as shown in our guide to installing SSL certificates with OpenSSL for Nginx. We tested this on Ubuntu 24.04 in our lab.
mkdir -p /tmp/secure-nginx/{certs,html,logs,temp}
cd /tmp/secure-nginx
openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -nodes -days 30 \
-keyout certs/test.key -out certs/test.crt -subj "/CN=localhost" \
-addext "subjectAltName=DNS:localhost,IP:127.0.0.1"
chmod 600 certs/test.keyStep 2: Put the security headers in one file
This file holds every security header. You include it in the server block and again in any location that adds its own header. We tested this on Ubuntu 24.04 in our lab.
# /tmp/secure-nginx/security-headers.conf
add_header Strict-Transport-Security "max-age=63072000" 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=()" always;
add_header Cross-Origin-Opener-Policy "same-origin" always;
add_header Content-Security-Policy-Report-Only "default-src 'self'; frame-ancestors 'none'; object-src 'none'; base-uri 'self'" always;Use the always flag on every header. Without it, Nginx adds the header only to 200, 201, 204, 206, 301, 302, 303, 304, 307 and 308 responses. So your 403, 404 and 500 pages would go out with no headers at all.
Step 3: Write the main config
This is the full secure Nginx configuration from our lab. On a production server, the same blocks go into /etc/nginx/nginx.conf (the http level settings) and your site file in /etc/nginx/sites-available/. We tested this on Ubuntu 24.04 in our lab.
# /tmp/secure-nginx/nginx.conf
worker_processes 1;
pid /tmp/secure-nginx/nginx.pid;
error_log /tmp/secure-nginx/logs/error.log warn;
events { worker_connections 256; }
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
client_body_temp_path /tmp/secure-nginx/temp/body;
proxy_temp_path /tmp/secure-nginx/temp/proxy;
fastcgi_temp_path /tmp/secure-nginx/temp/fastcgi;
uwsgi_temp_path /tmp/secure-nginx/temp/uwsgi;
scgi_temp_path /tmp/secure-nginx/temp/scgi;
access_log /tmp/secure-nginx/logs/access.log;
server_tokens off;
client_max_body_size 10m;
client_body_timeout 10s;
client_header_timeout 10s;
send_timeout 10s;
keepalive_timeout 15s;
limit_req_zone $binary_remote_addr zone=login:10m rate=5r/m;
limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;
limit_conn_zone $binary_remote_addr zone=peraddr:10m;
limit_req_status 429;
limit_conn_status 429;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ecdh_curve X25519:prime256v1:secp384r1;
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;
server {
listen 127.0.0.1:9080 default_server;
server_name _;
return 301 https://$host:9443$request_uri;
}
server {
listen 127.0.0.1:9443 ssl http2 default_server;
server_name localhost;
ssl_certificate /tmp/secure-nginx/certs/test.crt;
ssl_certificate_key /tmp/secure-nginx/certs/test.key;
root /tmp/secure-nginx/html;
index index.html;
autoindex off;
include /tmp/secure-nginx/security-headers.conf;
if ($request_method !~ ^(GET|HEAD|POST)$) { return 405; }
location ~ /\.(?!well-known) { deny all; }
location / {
try_files $uri $uri/ =404;
}
location /login/ {
limit_req zone=login burst=3 nodelay;
limit_conn peraddr 5;
add_header Cache-Control "no-store" always;
include /tmp/secure-nginx/security-headers.conf;
try_files $uri $uri/ =404;
}
location /api/ {
limit_req zone=api burst=20 nodelay;
limit_conn peraddr 10;
client_max_body_size 1m;
try_files $uri $uri/index.json =404;
}
}
}On a real server, the redirect line is simply return 301 https://$host$request_uri; and the ports are 80 and 443.
Step 4: Validate and start it
This checks the syntax and then starts the lab instance with its own config and prefix. We tested this on Ubuntu 24.04 in our lab.
nginx -t -c /tmp/secure-nginx/nginx.conf -p /tmp/secure-nginx/
nginx -c /tmp/secure-nginx/nginx.conf -p /tmp/secure-nginx/Our first attempt failed. We had used the newer http2 on; directive, and 1.24 does not know it:
nginx: [emerg] unknown directive "http2" in /tmp/secure-nginx/nginx.conf:54
nginx: configuration file /tmp/secure-nginx/nginx.conf test failedThe http2 on; directive arrived in Nginx 1.25.1. On Ubuntu’s 1.24, keep the older listen ... ssl http2; form. After that change, the test passed:
nginx: the configuration file /tmp/secure-nginx/nginx.conf syntax is ok
nginx: configuration file /tmp/secure-nginx/nginx.conf test is successfulTLS settings for a secure Nginx configuration
The cipher list above follows the “Intermediate” profile. Mozilla’s Server Side TLS guidelines and its SSL Configuration Generator have moved to the community TLSRef project, at docs.tlsref.org and configurator.tlsref.org. The current guidelines (version 6.0) still recommend Intermediate for most sites: TLS 1.2 and 1.3, ECDHE with AES-GCM or ChaCha20, and the client picks the cipher.
Version 6.0 also puts the hybrid post-quantum group X25519MLKEM768 first. However, that group needs OpenSSL 3.5 or later, and Ubuntu 24.04 ships 3.0.13. So we left it out of ssl_ecdh_curve.
Step 5: Check that old TLS versions are refused
This connects with each protocol version. For TLS 1.0 and 1.1, we lowered the client’s own security level, so that any refusal came from the server. We tested this on Ubuntu 24.04 in our lab.
echo | openssl s_client -connect 127.0.0.1:9443 -tls1 -cipher 'DEFAULT@SECLEVEL=0'
echo | openssl s_client -connect 127.0.0.1:9443 -tls1_1 -cipher 'DEFAULT@SECLEVEL=0'
echo | openssl s_client -connect 127.0.0.1:9443 -tls1_2
echo | openssl s_client -connect 127.0.0.1:9443 -tls1_3The server refused TLS 1.0 and 1.1 and accepted the other two:
tls1 ... tlsv1 alert protocol version ... SSL alert number 70
tls1_1 ... tlsv1 alert protocol version ... SSL alert number 70
tls1_2 New, TLSv1.2, Cipher is ECDHE-ECDSA-AES256-GCM-SHA384
tls1_3 New, TLSv1.3, Cipher is TLS_AES_256_GCM_SHA384Session tickets and OCSP stapling
Older guides tell you to add ssl_session_tickets off;. The TLSRef configurator only adds that line for Nginx versions before 1.23.2. Since 1.23.2, Nginx rotates ticket keys automatically when you use a shared ssl_session_cache, so 1.24 is fine with the shared cache shown above.
OCSP stapling has changed more. Let’s Encrypt removed OCSP URLs from its certificates on 7 May 2025 and turned its OCSP responders off on 6 August 2025. If you use Let’s Encrypt, ssl_stapling on; has nothing to staple, and Nginx will log a warning and ignore it. You can drop those lines. If your certificate comes from a CA that still runs OCSP, stapling still works, but you also need a resolver and ssl_trusted_certificate.
Security headers and the add_header trap
Here is what the lab server sent back. We tested this on Ubuntu 24.04 in our lab.
$ curl -skI https://127.0.0.1:9443/
HTTP/2 200
server: nginx
content-type: text/html
strict-transport-security: max-age=63072000
x-content-type-options: nosniff
x-frame-options: DENY
referrer-policy: strict-origin-when-cross-origin
permissions-policy: camera=(), microphone=(), geolocation=()
cross-origin-opener-policy: same-origin
content-security-policy-report-only: default-src 'self'; frame-ancestors 'none'; object-src 'none'; base-uri 'self'The server: nginx line no longer shows a version. The default 404 page also shows just nginx now.
A few notes on each header:
- HSTS: we left out
includeSubDomains. Add it only when every subdomain, including old intranet and mail hosts, works over HTTPS. Addpreloadonly after reading hstspreload.org, because removal from browser lists can take months. - X-Frame-Options and
frame-ancestors: both stop clickjacking. Modern browsers prefer the CSP directive, so we send both for older clients. - Content-Security-Policy: start with
Content-Security-Policy-Report-Only, watch the browser console and reports, then rename it toContent-Security-Policy. An enforced policy that is wrong will break your site. - Cross-Origin-Opener-Policy:
same-origincan break OAuth or payment popups that talk back to your page. Test those flows, and usesame-origin-allow-popupsif needed.
The inheritance trap
Nginx copies add_header lines from the server block into a location only if that location has no add_header of its own. So one innocent Cache-Control header wipes out all your security headers on that path. We added a test location with only add_header Cache-Control "no-store"; and got this:
$ curl -skI https://127.0.0.1:9443/trap/
HTTP/2 200
server: nginx
content-type: application/octet-stream
cache-control: no-storeThe response had no HSTS and no other security header. That is why the /login/ location above includes security-headers.conf again after its own add_header. As a result, /login/ sends both.
Rate limits, body size and timeouts
Login and API endpoints get the strictest limits. The login zone allows 5 requests per minute per IP, with a burst of 3. Then limit_conn caps open connections per IP. By default Nginx answers rejected requests with 503, so we set limit_req_status 429 to make the reason clear.
Step 6: Test the login rate limit
This sends six quick requests to /login/, once with the default status and once with 429. We tested this on Ubuntu 24.04 in our lab.
for i in $(seq 1 6); do
printf "%s " $(curl -sk -o /dev/null -w '%{http_code}' https://127.0.0.1:9443/login/)
done; echo200 200 200 200 503 503 # without limit_req_status
200 200 200 200 429 429 # with limit_req_status 429The first request plus the burst of 3 pass, then the rest are rejected. The error log records each one with limiting requests, excess: ... by zone "login", which is useful for fail2ban. Also, a 2 MB POST to /api/ (limit 1 MB) returned 413.
Short timeouts help against slow clients that hold connections open. Ten seconds for client_body_timeout and client_header_timeout suits most sites. However, raise them for large uploads on slow mobile links.
Hidden files, autoindex and methods
Step 7: Check dotfiles and methods
This requests a fake .env, a .git/config and an ACME challenge file, then tries two methods we did not allow. We tested this on Ubuntu 24.04 in our lab.
B=https://127.0.0.1:9443
for p in /.env /.git/config /.well-known/acme-challenge/test; do
printf "%-36s %s\n" "$p" "$(curl -sk -o /dev/null -w '%{http_code}' $B$p)"
done
echo "DELETE / -> $(curl -sk -o /dev/null -w '%{http_code}' -X DELETE $B/)"
echo "TRACE / -> $(curl -sk -o /dev/null -w '%{http_code}' -X TRACE $B/)"The output:
/.env 403
/.git/config 403
/.well-known/acme-challenge/test 200
DELETE / -> 405
TRACE / -> 405The regex location ~ /\.(?!well-known) blocks every path with a dot segment except .well-known, so certificate renewals keep working. Keep autoindex off (the default) unless you really need a file listing. Then use return 405 only for methods your app does not use. A REST API that needs PUT and DELETE should allow them.
The HTTP redirect also worked, and it kept the path and query string:
$ curl -sI "http://127.0.0.1:9080/login/?x=1"
HTTP/1.1 301 Moved Permanently
Location: https://127.0.0.1:9443/login/?x=1Step 8: Stop the lab instance
This stops the test server gracefully with the same config and prefix. We tested this on Ubuntu 24.04 in our lab.
nginx -s quit -c /tmp/secure-nginx/nginx.conf -p /tmp/secure-nginx/Behind a reverse proxy or load balancer
If Nginx proxies to an app, pass the client details and hide headers that leak your stack. We validated this block with nginx -t but did not run a backend behind it.
location / {
proxy_pass http://127.0.0.1:3000;
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_hide_header X-Powered-By;
proxy_connect_timeout 5s;
proxy_read_timeout 30s;
}If a load balancer sits in front of Nginx, use set_real_ip_from with that load balancer’s exact IP, plus real_ip_header X-Forwarded-For;. Never trust the header from everyone. Otherwise any client can fake its IP and dodge your rate limits.
Logging and patching
Add $request_time, $host and $http_x_forwarded_for to a custom log_format. Keep error logs at warn so rate limit hits show up. Then send both logs to a central place, so they survive if the server is compromised.
Ubuntu 24.04 ships Nginx 1.24 and backports security fixes into it, so the version number stays at 1.24.0. Upstream, nginx.org lists 1.30.6 as stable and 1.31.8 as mainline (October 2026). Stay on Ubuntu’s package unless you need new features, and run apt update && apt upgrade on a schedule. For this month’s fixes, see our post on checking and patching the NGINX October 2026 vulnerabilities.
Quick reference
This table sums up the main values from the secure Nginx configuration above.
| Setting | Value we used | Why |
|---|---|---|
server_tokens | off | Hides the version |
ssl_protocols | TLSv1.2 TLSv1.3 | Intermediate profile |
ssl_session_cache | shared, 10m | Resumption, ticket key rotation |
| HSTS max-age | 63072000 | Two years, as in TLSRef |
limit_req login | 5r/m, burst 3 | Slows password guessing |
client_max_body_size | 10m site, 1m API | Stops huge uploads |
| Timeouts | 10s | Drops slow clients |
India angle
The CERT-In Directions of 28 April 2022 require organisations to keep logs of their ICT systems for a rolling 180 days, stored within India. They also require cyber incidents to be reported within 6 hours of noticing them. So your Nginx access and error logs should go to storage that keeps them for at least that long.
Quick checklist
- ☐
server_tokens off;in thehttpblock - ☐ TLS 1.2 and 1.3 only, Intermediate cipher list
- ☐ HTTP redirects to HTTPS with a 301
- ☐ HSTS sent;
includeSubDomainsandpreloadonly after checking every subdomain - ☐ Security headers in one include file, all with
always - ☐ Every location with its own
add_headerincludes the headers file again - ☐ CSP running in Report-Only before enforcing
- ☐
limit_reqandlimit_connon login and API paths - ☐ Body size and timeouts set
- ☐ Dotfiles blocked,
autoindex off, unused methods return 405 - ☐
set_real_ip_fromlimited to your own proxy IPs - ☐
nginx -tpasses, and Nginx updates are on a schedule
Test your own site
After you deploy, run your domain through our free website safety check, and also through securityheaders.com and SSL Labs. A full web application VAPT goes further and tests the app behind Nginx. If you want someone to review this secure Nginx configuration along with the rest of the server, our Linux server hardening audit covers it.
Related guides
- How to Install Nginx on CentOS Stream, Rocky Linux and AlmaLinux
- How to Set Up an SSL Certificate for Nginx: Let’s Encrypt and OpenSSL
- Nginx Interview Questions and Answers (2026)
- How to Audit Web Servers and Web Applications: Checklist
Sources
- nginx: ngx_http_headers_module (add_header and always)
- nginx: ngx_http_limit_req_module
- nginx: ngx_http_ssl_module
- nginx: download page (stable and mainline versions)
- TLSRef: Server Side TLS guidelines
- TLSRef: TLS Configurator (formerly Mozilla SSL Configuration Generator)
- Let’s Encrypt: Ending OCSP Support in 2025
- OWASP Secure Headers Project
- HSTS Preload List submission
- CERT-In Directions under Section 70B, 28 April 2022 (PDF)
Running Linux servers in production? Our Linux server hardening & security audit checks configuration, patching, SSH and logging. You can also use our free Linux server hardening checklist, or contact us.
