Layer 1: default_server catch-all and hiding the version
Every public IP on the internet is constantly scanned by IP address and random hostnames. Without an explicit
default_server, nginx answers those probes with the first configured site and exposes its TLS certificate.
Put the catch-all in a separate file /etc/nginx/conf.d/00-default.conf and delete the stock default.conf.
server {
listen 80 default_server;
listen [::]:80 default_server;
server_name _;
return 444;
}Code 444 is an internal nginx status: it drops the TCP connection immediately without sending HTTP headers or a body, saving bandwidth on scanners. Include listen [::]:80 if the server has IPv6 enabled.
server {
listen 443 ssl default_server;
listen [::]:443 ssl default_server;
server_name _;
ssl_reject_handshake on;
}On port 443, abort the TLS handshake before sending any certificate (ssl_reject_handshake on works from nginx 1.19.4+). IP scanners cannot discover which domains live on the host.
In the http context (inside /etc/nginx/nginx.conf or /etc/nginx/conf.d/01-hardening.conf), disable printing the exact nginx version in the Server header and error pages:
server_tokens off;
Responses then send Server: nginx without a version number. Stripping the word nginx completely requires a third-party module (headers-more), but hiding the version already cuts off automated scanners hunting for specific unpatched releases.
Layer 2: size limits and Slowloris timeouts
Slowloris and similar slow-rate attacks open thousands of connections and trickle request headers or bodies one byte every few seconds to tie up worker sockets. The default 60-second nginx timeouts give slow clients far too much room.
server_tokens off;
reset_timedout_connection on;Hide the nginx version and force-close timed-out sockets (reset_timedout_connection on sends RST and immediately frees socket buffer memory).
default:server_tokens onreset_timedout_connection off
client_header_timeout 10s;
client_body_timeout 15s;
send_timeout 15s;
keepalive_timeout 30s;Cut waits for slow headers, request bodies, and client reads from 60 seconds down to 10–15 seconds. Raise client_body_timeout only inside specific location blocks that accept large uploads.
default:client_header_timeout 60sclient_body_timeout 60ssend_timeout 60s
client_max_body_size 1m;
client_body_buffer_size 16k;
client_header_buffer_size 1k;
large_client_header_buffers 4 8k;Cap default body and header buffer sizes. Keep client_max_body_size 1m small globally and raise it only on upload endpoints (media libraries, attachment forms).
default:client_max_body_size 1mclient_body_buffer_size 8k/16klarge_client_header_buffers 4 8k
Layer 3: HTTP methods and hidden files
A static site or public landing page needs only GET and HEAD (limit_except permits HEAD automatically alongside GET):
location / {
limit_except GET HEAD {
deny all;
}
try_files $uri $uri/ =404;
}
# Block .git, .env, .htpasswd while keeping .well-known open for Let's Encrypt
location ~ /\.(?!well-known) {
deny all;
}
Any POST, PUT, DELETE, or TRACE hitting that location gets 403 Forbidden before reaching anything behind it. On API routes, list the exact methods you need inside location /api/.
Layer 4: security headers snippet
Keep the base security headers in /etc/nginx/snippets/headers.conf so you can pull them in with one line (include snippets/headers.conf;) at the server level and inside any location that defines its own add_header (Config anatomy).
add_header X-Content-Type-Options "nosniff" always;Stops browsers from MIME-sniffing files by content: an uploaded image containing text will not execute as a script. The always flag ensures the header is sent on 4xx/5xx error pages too.
add_header X-Frame-Options "DENY" always;Blocks embedding the site in an <iframe> on other domains (clickjacking protection). Use SAMEORIGIN if the site must load inside frames on the same origin.
add_header Referrer-Policy "strict-origin-when-cross-origin" always;When following an external link, sends only the origin (https://example.org) instead of the full path and query parameters that might hold password-reset tokens.
add_header Permissions-Policy "geolocation=(), microphone=(), camera=()" always;Disables access to geolocation, microphone, and camera for all scripts on the page.
add_header Content-Security-Policy "default-src 'self'; base-uri 'self'; object-src 'none'; frame-ancestors 'none'" always;Baseline Content-Security-Policy for a site without third-party scripts: loads resources only from its own origin and blocks framing (frame-ancestors 'none'). For sites with external APIs or analytics, add the required origins to connect-src and script-src after testing under Content-Security-Policy-Report-Only.
Leave X-XSS-Protection out of modern configs: browsers removed their built-in XSS auditors years ago, and the old 1; mode=block header could introduce data leaks in edge cases.
How to check
- Validate syntax and reload:
sudo nginx -t && sudo systemctl reload nginx - Verify that the version is hidden and security headers are present:
curl -sI https://example.org/ | grep -iE '^(server|x-content|x-frame|referrer|permissions|content-security):' # server: nginx # x-content-type-options: nosniff # x-frame-options: DENY # referrer-policy: strict-origin-when-cross-origin # permissions-policy: geolocation=(), microphone=(), camera=() # content-security-policy: default-src 'self'; ... - Verify disallowed HTTP methods and hidden files return
403:curl -s -o /dev/null -w "DELETE:%{http_code}\n" -X DELETE https://example.org/ # DELETE:403 curl -s -o /dev/null -w ".env:%{http_code}\n" https://example.org/.env # .env:403 - Confirm the same security headers stay intact on
/assets/and on404responses:curl -sI https://example.org/no-such-page | grep -iE '^(HTTP/|x-frame|content-security)'
If it doesn’t work
After adding Content-Security-Policy, inline scripts, fonts, or images from a third-party CDN stopped loading
- Cause
- A strict
default-src 'self'policy blocks external origins and inline<script>tags without a hash ornonce. - Fix
- Roll out the policy in observation mode first using
Content-Security-Policy-Report-Only, review blocked resources in browser DevTools, and switch toContent-Security-Policyonce the allowlist is complete.
Security headers show up on the home page but disappear on /assets/ or /api/
- Cause
- Those
locationblocks define their ownadd_header(such asCache-Control), which overrides allserver-leveladd_headerdirectives (Config anatomy). - Fix
- Add
include snippets/headers.conf;inside everylocationthat defines its ownadd_header.
REST API PUT or DELETE requests return 403 Forbidden
- Cause
limit_except GET HEAD { deny all; }was applied site-wide without excluding/api/.- Fix
- Scope method restrictions to static routes only, and explicitly list the required methods (
GET HEAD POST PUT PATCH DELETE) inside/api/.
Large cookies or long query URLs fail with 400 Request Header Or Cookie Too Large
- Cause
- A tight
large_client_header_bufferssetting (such as2 4k) cannot fit a large JWTAuthorizationheader or oversized cookies. - Fix
- Raise it back to
4 8k(the nginx default) and check whether the app is inflating cookies unnecessarily.
Hitting the server’s IP directly on port 80 returns 404 or another site instead of closing the connection
- Cause
- No dedicated
listen 80 default_server;block is active, or the stockdefault.confis still sitting inconf.d/. - Fix
- Remove the stock
/etc/nginx/conf.d/default.confand add00-default.confwithreturn 444;on port 80 andssl_reject_handshake on;on port 443.