0
0
NginxHow-ToBeginner · 3 min read

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

DirectivePurposeExample
add_headerAdds HTTP headers to responsesadd_header X-Content-Type-Options nosniff;
nosniffValue to prevent MIME sniffingUsed as header value
server blockScope to apply header globallyPlace add_header inside server block
location blockScope to apply header to specific pathsPlace 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.