大网数据广告活动
网站运营与故障问答

Is it necessary to specify content-type in http response header?

· 52CE 我爱测

Except for the html document, currently all the files (css, javascript and images) served from my web server do not specify the content-type in the http response header. I happen to notice this as I intend to remove the type attr…

问题原文

原帖链接 · Question Overflow · CC BY-SA 3.0

Except for the html document, currently all the files (css, javascript and images) served from my web server do not specify the content-type in the http response header. I happen to notice this as I intend to remove the type attribute in both my script tag and link tag, but came across this answer which says the following:

The MIME type is also sent via the HTTP Content-Type header, so using type="text/css" would only be extra bytes.

已采纳解答

原帖链接 · Jukka K. Korpela · CC BY-SA 4.0

Yes. By the HTTP protocol, clause 7.2.1:

“Any HTTP/1.1 message containing an entity-body SHOULD include a Content-Type header field defining the media type of that body. If and only if the media type is not given by a Content-Type field, the recipient MAY attempt to guess the media type via inspection of its content and/or the name extension(s) of the URI used to identify the resource.”

So yes, the response headers should contain Content-Type header for any response data (called “entity-body” in the protocol, often “file” in common language). If it is omitted, the browser is allowed to make its own wild guesses on the type of data it got. In many contexts, the risk of wrong guesses is negligible, but this not a good excuse for violating the protocol.

Attributes like type=text/css and type=text/javascript have not been necessary, except by some formal specifications, or even useful. Even if a server incorrectly sends e.g. CSS data without Content-Type, browsers will treat the data as CSS if <link rel=stylesheet ...> was the element that caused the request. It’s the rel attribute that matters in that case.

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Webmasters Stack Exchange
适用范围
以原帖系统、软件版本与发布日期为准(2013-12-03)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 3.0 / CC BY-SA 4.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。