How to Configure X-Content-Type-Options Header in Nginx
To configure
X-Content-Type-Options in Nginx, add the directive add_header X-Content-Type-Options nosniff; inside your server or location block. This header tells browsers not to guess the content type, improving security against some attacks.Syntax
The add_header directive in Nginx is used to add HTTP headers to responses. For X-Content-Type-Options, the syntax is:
add_header: Nginx directive to add a header.X-Content-Type-Options: The header name.nosniff: The header value that disables MIME type sniffing.
nginx
add_header X-Content-Type-Options nosniff;
Example
This example shows how to add the X-Content-Type-Options header globally in the server block of your Nginx configuration. It ensures all responses include this security header.
nginx
server {
listen 80;
server_name example.com;
add_header X-Content-Type-Options nosniff;
location / {
root /var/www/html;
index index.html;
}
}Output
When you request a page, the HTTP response headers will include:
X-Content-Type-Options: nosniff
Common Pitfalls
One common mistake is placing the add_header directive inside a block where it does not apply to all responses, such as only inside a location block but missing others. Also, if you use add_header with always flag incorrectly, it might not behave as expected in older Nginx versions.
Another pitfall is forgetting to reload or restart Nginx after changing the configuration, so the header does not appear.
nginx
## Wrong: Header only in one location, missing others
server {
listen 80;
server_name example.com;
location /images/ {
add_header X-Content-Type-Options nosniff;
}
}
## Right: Header added globally
server {
listen 80;
server_name example.com;
add_header X-Content-Type-Options nosniff;
}Quick Reference
| Directive | Purpose | Example |
|---|---|---|
| add_header | Adds HTTP headers to responses | add_header X-Content-Type-Options nosniff; |
| nosniff | Value to prevent MIME sniffing | Used as header value |
| server block | Scope to apply header globally | Place add_header inside server block |
| location block | Scope to apply header to specific paths | Place add_header inside location block |
Key Takeaways
Use add_header X-Content-Type-Options nosniff; inside your server or location block to set the header.
Place the directive in the correct scope to ensure all desired responses include the header.
Reload or restart Nginx after configuration changes to apply the header.
This header improves security by preventing browsers from guessing content types.
Avoid placing add_header only in limited locations unless intentional.