Course contentsShow
← Software Engineering
Lesson 1074 of 1,93332. Security EngineeringFree lesson

X-Content-Type-Options and MIME Sniffing

Preventing browsers from MIME-sniffing responses away from declared content types to block execution attacks.

X-Content-Type-Options and MIME Sniffing

You'll learn how to prevent browsers from second-guessing your server's declared content types, closing a dangerous execution attack vector.

The Problem: MIME Sniffing

Browsers historically tried to be "helpful" by examining response bodies to detect the actual file type, even when the server declared a specific Content-Type header. This behavior is called MIME sniffing or content sniffing.

Think of it like a mail carrier opening your envelope to verify the contents match the label—except in this case, the "help" creates security holes.

The Attack Vector

Imagine an attacker uploads a malicious file disguised as an image (malicious.jpg) to your site. Your server correctly serves it with Content-Type: image/jpeg. But if the file contains hidden HTML/JavaScript and the browser MIME-sniffs it, the browser might execute it as HTML, ignoring your declared type. Result: XSS attack.

This commonly happens when user-uploaded content is served from the same domain as your application.

The Defense: X-Content-Type-Options

The X-Content-Type-Options header has one job: tell browsers to trust your Content-Type declaration and stop guessing.

X-Content-Type-Options: nosniff

That's it. One value: nosniff.

When set, modern browsers will:

  • Refuse to render stylesheets if not served as text/css
  • Block script execution if not served as valid JavaScript MIME types
  • Respect declared content types for all resources

This header works alongside your Content Security Policy and other security headers as part of defense in depth.

Key Takeaway: Always set X-Content-Type-Options: nosniff to prevent browsers from MIME-sniffing responses away from declared types, blocking a class of content-based execution attacks.