How to add custom HTTP headers
Add your own HTTP response headers - most often security headers - with a small piece of custom Nginx configuration.
Before you start
- SSH access to the host - see SSH access.
- Add the headers in
~/nginx/50main.conf- see custom Nginx configuration.
Add security headers
In the server block (or a location), use add_header with the always flag so the header is sent
on error responses too:
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
Important
If you add add_header inside a location, Nginx stops inheriting the headers set higher up - you
must repeat the ones you still want in that location.
Restrict access to text and log files
A common hardening rule: allow robots.txt, but deny other .txt and .log files.
location = /robots.txt {
allow all;
log_not_found off;
access_log off;
}
location ~* \.(txt|log)$ {
deny all;
}
Apply and verify
tscli nginx reload
Check the headers with:
curl -I https://example.com
Tip
To make browsers always use HTTPS, add the Strict-Transport-Security (HSTS) header - but only
once HTTPS works everywhere, because it is hard to undo. See Force HTTPS.
If it did not work
A header that is missing from curl -I usually lost to another add_header set. Nginx keeps only
the nearest set of add_header lines, and the platform already sends X-Frame-Options,
X-Xss-Protection and Referrer-Policy on every site. Put yours in location / to replace them.
If tscli nginx reload refused the change, its output names the file and line. See
Finding and reading logs, or
contact support.