Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 30 ยท Security and Hardening

Hardening and Security Headers

Harden nginx and Apache: hide version tokens, set HSTS, CSP and nosniff headers, block dotfiles and backups, run workers unprivileged and cap requests.

A freshly installed web server is tuned for "works out of the box", not for "survives the internet". It announces its exact version to anyone who asks, loads modules you never use, and will happily serve a forgotten config.php.bak if somebody uploads one. Hardening is the habit of closing those small doors: say less, load less, allow less, and tell browsers to be strict on your behalf.

This lesson covers the changes that give the most protection for the least effort. They are all a few lines each, and they work on both servers. The big idea is defense in depth: your application should still be secure, but the web server is a second wall, and a few of its settings (like HTTPS-only headers) can only be set here.

Real nginx and Apache configuration appears in read-only blocks, because the site cannot run a web server. The interactive examples are JavaScript stand-ins: a header grader and a path-blocking checker that model the rules. They are not security scanners.

Hardening in four moves

Say less Hide versions and error details.
Load less Disable modules and features you do not use.
Allow less Block dotfiles, backups, big bodies, slow clients.
Tell browsers Send security headers on every response.

Each move is small. Together they remove most easy targets.

1 / 2

Say less: version tokens

By default both servers print their name and version in the Server response header and on built-in error pages. That helps nobody except an attacker choosing which known bug to try.

NGINX
http {
    server_tokens off;      # "Server: nginx" without the version, and no version on error pages
}
APACHE
ServerTokens Prod           # "Server: Apache" only
ServerSignature Off         # no version footer on error pages and directory listings
TraceEnable Off             # refuse the TRACE method

This is not security through obscurity in the bad sense. You are not relying on secrecy, you are just not volunteering information. Keep patching regardless. Note that stock nginx can drop the version but not the name nginx; removing the whole header needs an extra module, which is rarely worth it. Also strip headers added by the application, for example PHP's X-Powered-By (set expose_php = Off in php.ini, or hide it at the proxy with proxy_hide_header X-Powered-By;).

Load less: modules and features

Every loaded module is code that can have bugs and configuration that can be wrong. List what you have and remove what you do not use:

Terminal
apachectl -M                      # loaded Apache modules
sudo a2dismod status autoindex    # Debian: disable two modules
nginx -V 2>&1 | tr ' ' '\n' | grep -- --with     # nginx build options

Directory listings are the easiest example. If there is no index.html, a server with listings enabled shows every file in the folder. nginx's autoindex is off by default, so just never turn it on carelessly. Apache needs it spelled out:

APACHE
<Directory "/var/www">
    Options -Indexes -Includes
</Directory>

Also remove default content: the welcome page, sample CGI scripts and the /server-status or stub_status endpoints unless you restrict them to your own addresses (see Access Control and Rate Limiting).

Allow less: block secrets, run unprivileged, limit requests

Dotfiles and backup files

Deployments leave things behind: .git folders, .env files with passwords, editor backups such as index.php~, database dumps. The best fix is to keep them out of the document root completely. The second-best fix is a rule that refuses them:

NGINX
# deny hidden files, but keep .well-known for certificate validation
location ~ /\.(?!well-known/) {
    deny all;
}

# deny backup, dump and editor leftovers
location ~* (\.(bak|old|orig|save|sql|swp|dist)|~)$ {
    deny all;
}
APACHE
<DirectoryMatch "/\.(?!well-known)">
    Require all denied
</DirectoryMatch>

<FilesMatch "^\.|(\.(bak|old|orig|save|sql|swp|dist)|~)$">
    Require all denied
</FilesMatch>

Apache needs two containers because it matches directories and files separately: <DirectoryMatch> catches everything inside a folder such as .git/, and <FilesMatch> catches single files such as .env. The (?!well-known/) part is a negative lookahead: "a dot segment that is not .well-known/". Let's Encrypt validates domains through /.well-known/acme-challenge/, so blocking all dotfiles blindly breaks certificate renewal (see HTTPS, TLS and Let's Encrypt). Try the patterns on a list of paths:

JS Stand-in: which paths get blocked?

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Note that /blog/old-posts/ is served: the backup rule only matches the end of the path. Patterns like these are safety nets, not guarantees, so anchor them and test them on paths you care about.

Do not run workers as root

Binding ports 80 and 443 needs privileges, so the master process starts as root. It then starts worker processes that handle the actual (untrusted) requests, and those must run as an unprivileged account:

NGINX
user www-data;              # Debian; "nginx" on RHEL
worker_processes auto;
APACHE
User  www-data
Group www-data

If a bug lets an attacker run code inside a worker, they get that account's rights, not the machine's. Give that account read access to the site and write access only to the folders that really need it (uploads, cache). Never make the web root writable by the server user "to fix a permissions error". In containers, prefer an image that runs unprivileged on a high port such as 8080.

Limit request size and speed

Open-ended requests are an invitation to exhaust memory, disk or connections. Set limits that match what your site really needs:

NGINX
client_max_body_size   10m;      # reject larger uploads with 413
client_header_timeout  10s;
client_body_timeout    10s;
send_timeout           15s;
keepalive_timeout      15s;
large_client_header_buffers 4 8k;
APACHE
LimitRequestBody 10485760        # 10 MB
Timeout 30
KeepAliveTimeout 5
RequestReadTimeout header=20-40,MinRate=500 body=20,MinRate=500

RequestReadTimeout (from mod_reqtimeout) is Apache's answer to slow clients that trickle their request one byte at a time to keep connections occupied. Raise a limit on purpose for the one location that needs it (an upload form) instead of globally.

Tell browsers: security headers

Browsers have strong protections that stay off until the server asks. A few response headers turn them on:

Header What it does
Strict-Transport-Security (HSTS) After one HTTPS visit, the browser refuses plain HTTP for this site for max-age seconds.
Content-Security-Policy Lists where scripts, styles, images and frames may come from, which limits the damage of injected scripts.
X-Content-Type-Options: nosniff Stops the browser from guessing a file's type, so an uploaded text file cannot run as a script.
X-Frame-Options or CSP frame-ancestors Controls who may embed your pages in a frame, which prevents clickjacking.
Referrer-Policy Controls how much of your URL is sent to other sites.
Permissions-Policy Switches off browser features such as camera or geolocation for your pages.
NGINX
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-Frame-Options "SAMEORIGIN" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
add_header Permissions-Policy "camera=(), microphone=(), geolocation=()" always;
add_header Content-Security-Policy "default-src 'self'; img-src 'self' data:; frame-ancestors 'self'; base-uri 'self'; form-action 'self'" always;
APACHE
Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains"
Header always set X-Content-Type-Options "nosniff"
Header always set X-Frame-Options "SAMEORIGIN"
Header always set Referrer-Policy "strict-origin-when-cross-origin"
Header always set Permissions-Policy "camera=(), microphone=(), geolocation=()"
Header always set Content-Security-Policy "default-src 'self'; img-src 'self' data:; frame-ancestors 'self'; base-uri 'self'; form-action 'self'"

Apache needs mod_headers (a2enmod headers).

Two gotchas: always and inheritance

Without always, nginx's add_header only adds the header to successful and redirect statuses (200, 201, 204, 206, 301, 302, 303, 304, 307, 308), and Apache's plain Header set skips error responses. Your 404 and 500 pages would then miss the headers. Use always on both.

nginx has a second, nastier rule: add_header directives are inherited from the level above only if the current level defines none of its own. If you set five headers in server and then add one add_header Cache-Control ... inside a location, the five server-level headers vanish for that location. Put the shared headers in a snippet and include it in every block that adds its own (see Nginx Configuration Syntax).

Roll out HSTS and CSP carefully

HSTS is powerful and sticky. Browsers only honor it when it arrives over HTTPS, and a long max-age locks visitors into HTTPS even if your certificate breaks. Start with max-age=300, confirm that every subdomain works on HTTPS, then raise it (a year is typical). Add includeSubDomains only when you are sure about all subdomains, and think hard before using preload, because removal from browser lists takes months.

A strict CSP breaks pages that use inline scripts, so introduce it with Content-Security-Policy-Report-Only first. The browser then reports violations in the console without blocking anything, and you tighten the policy until it is quiet. Because a good CSP is closely tied to the application, many teams set it in the app and let the server set the simple headers.

Now try a grader that checks a response the way an audit tool would:

JS Stand-in: grade a response's security headers

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The third case shows why "has a header" is not the same as "is protected": a one-hour HSTS and a CSP that allows everything look present but earn little. To check a real site, run curl -sI https://example.com and read the headers yourself, which is also the first step in Logs and Troubleshooting.

After changing headers, reload (nginx -t && systemctl reload nginx, or apachectl configtest && systemctl reload apache2) and fetch the page with curl -I from outside. Also load a 404 page: it is where a missing always shows up.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why do you add always to add_header (nginx) and use Header always set (Apache)?

    Without always, the headers are only added to successful and redirect responses. Error pages would be missing them.
  2. 2. You define five add_header lines in an nginx server block, then add one add_header inside a location. What happens in that location?

    add_header is inherited only when the current level has no add_header of its own. Use an included snippet to repeat the shared headers.
  3. 3. Why must a rule that blocks dotfiles exclude /.well-known/?

    The ACME HTTP challenge fetches a file from /.well-known/acme-challenge/. A blanket dotfile rule would make that request fail with 403.
  4. 4. Which account should handle requests in nginx and Apache worker processes?

    The master starts as root to bind ports 80 and 443, but workers handle untrusted input and must run as a user with minimal rights.
  5. 5. What is the safest way to start using a strict Content-Security-Policy on an existing site?

    Report-only mode reports violations without blocking, so you can tighten the policy until the site works under it.

Summary

  • Say less: server_tokens off; for nginx, ServerTokens Prod, ServerSignature Off and TraceEnable Off for Apache; hide X-Powered-By.
  • Load less: disable unused modules, keep listings off (Options -Indexes), remove default pages and restrict status endpoints.
  • Allow less: block dotfiles (except .well-known) and backup files, keep secrets outside the document root, run workers as an unprivileged user, and cap body size and timeouts.
  • Security headers (HSTS, CSP, nosniff, framing, Referrer-Policy, Permissions-Policy) switch on browser protections; use always so error pages carry them.
  • nginx add_header inheritance is all-or-nothing per level, so share headers through an include.
  • Introduce HSTS with a short max-age and CSP in report-only mode before enforcing.

Next: Logs and Troubleshooting.