📜  HTTP 标头 | X-Content-Type-Options(1)

📅  最后修改于: 2023-12-03 14:42:00.191000             🧑  作者: Mango

HTTP 标头 | X-Content-Type-Options

简介

X-Content-Type-Options 是一个 HTTP 响应头部,用于向客户端(如浏览器)指示服务器在提供资源时,不要执行 MIME 类型嗅探(MIME-Type sniffing),而应该坚持使用 Content-Type 头部指定的类型。

通常情况下,浏览器在无法准确判断资源的 MIME 类型时,会采用 MIME-Type 嗅探的方式来确定资源的类型。但是,由于 MIME-Type 嗅探存在安全隐患,因此该头部可以帮助缓解这种风险。

用法

在服务器向客户端提供资源时,将 X-Content-Type-Options 设为 nosniff 即可开启这个功能。

HTTP/1.1 200 OK
Content-Type: text/html; charset=UTF-8
X-Content-Type-Options: nosniff
示例

以下是一个示例,展示如何在 Web 应用程序中设置 X-Content-Type-Options 头部:

Node.js 示例
const http = require('http');
const port = 3000;

const requestHandler = (request, response) => {
    response.setHeader('X-Content-Type-Options', 'nosniff');
    response.setHeader('Content-Type', 'text/html');
    response.end('<html><head><title>X-Content-Type-Options</title></head><body><h1>Hello World!</h1></body></html>');
}

const server = http.createServer(requestHandler);

server.listen(port, (err) => {
    if (err) {
        return console.log('Something went wrong', err);
    }

    console.log(`Server is listening on ${port}`);
})
PHP 示例
header('X-Content-Type-Options: nosniff');
header('Content-Type: text/html');

echo '<html><head><title>X-Content-Type-Options</title></head><body><h1>Hello World!</h1></body></html>';
ASP.NET 示例
protected void Page_Load(object sender, EventArgs e)
{
    Response.Headers["X-Content-Type-Options"] = "nosniff";
    Response.ContentType = "text/html";
    Response.Write("<html><head><title>X-Content-Type-Options</title></head><body><h1>Hello World!</h1></body></html>");
}
总结

通过配置 X-Content-Type-Options 头部,可以强制浏览器使用 Content-Type 头部指定的 MIME 类型,避免 MIME-Type 嗅探带来的潜在风险。应用程序开发人员可以通过在服务器端设置该头部来增加 Web 应用程序的安全性。