How to Configure X-XSS-Protection Header in Nginx
To configure
X-XSS-Protection in Nginx, add the header using the add_header directive inside your server or location block. For example, add_header X-XSS-Protection "1; mode=block" always; enables the browser's XSS filter and blocks detected attacks.Syntax
The add_header directive in Nginx sets HTTP headers in responses. To configure X-XSS-Protection, use:
add_header X-XSS-Protection "value" [always];wherevaluecontrols the XSS filter behavior.- Common values include
"1; mode=block"to enable and block attacks, or"0"to disable.
nginx
add_header X-XSS-Protection "1; mode=block" always;Example
This example shows how to enable the XSS protection header globally in an Nginx server block. It tells browsers to block detected cross-site scripting attacks.
nginx
server {
listen 80;
server_name example.com;
add_header X-XSS-Protection "1; mode=block" always;
location / {
root /var/www/html;
index index.html;
}
}Output
When a browser requests a page, the response header will include:
X-XSS-Protection: 1; mode=block
Common Pitfalls
Common mistakes when configuring X-XSS-Protection in Nginx include:
- Placing
add_headerinsideifblocks or locations withoutalways, causing headers to be skipped. - Not using
alwayswhen needed, so headers are missing on error responses. - Using deprecated or unsupported values.
To ensure the header is always set, use add_header X-XSS-Protection "1; mode=block" always;
nginx
## Wrong way (header may not appear on errors) add_header X-XSS-Protection "1; mode=block"; ## Right way (header always set) add_header X-XSS-Protection "1; mode=block" always;
Quick Reference
| Value | Effect |
|---|---|
| "1; mode=block" | Enable XSS filter and block attacks |
| "1" | Enable XSS filter but do not block, only sanitize |
| "0" | Disable XSS filter |
| "1; report=https://example.com/report" | Enable filter and report attacks to URL |
Key Takeaways
Use the add_header directive to set X-XSS-Protection in Nginx.
The value "1; mode=block" enables and blocks XSS attacks in supported browsers.
Add the always flag to ensure the header is sent on all responses.
Avoid placing add_header inside conditional blocks without always.
Check browser support as some modern browsers have deprecated this header.