What is X-Content-Type-Options?
When the browser receives a file from the server, it looks at the
Content-Type header to understand what kind of file it is —
an HTML page, an image, JavaScript, CSS, and so on. But if the Content-Type
is not specified or is set incorrectly, the browser tries to guess the file
type on its own by analyzing its content. This feature is called MIME-sniffing.
The problem is that MIME-sniffing gives attackers certain opportunities.
An attacker can upload a file to your site that looks like a regular image
but actually contains JavaScript code inside. Without proper protection,
the browser may recognize this file as a script and execute it — even if
the server sent it with a type of image/png or
text/plain.
The X-Content-Type-Options header with the value nosniffprevents the browser from guessing the file type. The browser will strictly
trust the Content-Type specified by the server and will not attempt to
interpret the file differently. If the server says it's an image — the
browser will treat it as an image and under no circumstances execute it
as a script.
How to enable X-Content-Type-Options?
To prevent the browser from guessing file types (MIME-sniffing), add the following header to your web server configuration. Choose the example below depending on which server you use.
Nginx
add_header X-Content-Type-Options "nosniff" always;Apache
Header set X-Content-Type-Options "nosniff"Important note
This header has only one valid value — nosniff.
It's either set or it's not. No additional parameters or
settings are required.
Make sure your server sends correct Content-Type values —
after enabling nosniff, the browser will strictly follow
the type specified by the server. If a CSS file is served with a type of
text/plain, the browser will refuse to apply it. Verify that
all your files are served with the correct Content-Type.
Especially important for sites with file uploads — if users can upload files to your site, this header is critically necessary. It will prevent the browser from executing an uploaded file as code, even if an attacker disguises a script as an image.
No reason not to enable it — this header has no side effects when the server is configured correctly. Adding it takes one line and instantly closes an entire class of attacks.
Enable X-Content-Type-Options — it's the simplest security header that can be set up in seconds, yet it provides serious protection.