TRACE - HTTP

TRACE
=====

The **HTTP `TRACE` method** performs a message loop-back test along the path to the target resource, providing a useful debugging mechanism.

The final recipient of the request should reflect the message received, excluding any fields that might include sensitive data, back to the client as the message body of a `200` (`OK`) response with a `Content-Type` of `message/http`. The final recipient is either the origin server or the first server to receive a `Max-Forwards` value of 0 in the request.

Note that the client must not send content in the request, or generate fields that might include sensitive data, such as stored user credentials or cookies.

|  |  |
| --- | --- |
| Request has body | No |
| Successful response has body | Yes |
| Safe | Yes |
| Idempotent | Yes |
| Cacheable | No |
| Allowed in HTML forms | No |

Syntax
------

```http
TRACE /index.html
```

Specifications
--------------

| Specification |
| --- |
| HTTP Semantics # TRACE |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* HTTP methods


PATCH - HTTP

PATCH
=====

The **HTTP `PATCH` request method** applies partial modifications to a resource.

`PATCH` is somewhat analogous to the "update" concept found in CRUD (in general, HTTP is different than CRUD, and the two should not be confused).

A `PATCH` request is considered a set of instructions on how to modify a resource. Contrast this with `PUT`; which is a complete representation of a resource.

A `PATCH` is not necessarily idempotent, although it can be. Contrast this with `PUT`; which is always idempotent. The word "idempotent" means that any number of repeated, identical requests will leave the resource in the same state. For example if an auto-incrementing counter field is an integral part of the resource, then a `PUT` will naturally overwrite it (since it overwrites everything), but not necessarily so for `PATCH`.

`PATCH` (like `POST`) *may* have side-effects on other resources.

To find out whether a server supports `PATCH`, a server can advertise its support by adding it to the list in the `Allow` or `Access-Control-Allow-Methods` (for CORS) response headers.

Another (implicit) indication that `PATCH` is allowed, is the presence of the `Accept-Patch` header, which specifies the patch document formats accepted by the server.

|  |  |
| --- | --- |
| Request has body | Yes |
| Successful response has body | May |
| Safe | No |
| Idempotent | No |
| Cacheable | Only if freshness information is included |
| Allowed in HTML forms | No |

Syntax
------

```http
PATCH /file.txt HTTP/1.1
```

Example
-------

### Request

```http
PATCH /file.txt HTTP/1.1
Host: www.example.com
Content-Type: application/example
If-Match: "e0023aa4e"
Content-Length: 100

[description of changes]
```

### Response

A successful response is indicated by any 2xx status code.

In the example below a `204` response code is used, because the response does not carry a payload body. A `200` response could have contained a payload body.

```http
HTTP/1.1 204 No Content
Content-Location: /file.txt
ETag: "e0023aa4f"
```

Specifications
--------------

| Specification |
| --- |
| RFC 5789  |

See also
--------

* `204`
* `Allow`, `Access-Control-Allow-Methods`
* `Accept-Patch` – specifies the patch document formats accepted by the server.


OPTIONS - HTTP

OPTIONS
=======

The **HTTP `OPTIONS` method** requests permitted communication options for a given URL or server. A client can specify a URL with this method, or an asterisk (`*`) to refer to the entire server.

|  |  |
| --- | --- |
| Request has body | No |
| Successful response has body | May |
| Safe | Yes |
| Idempotent | Yes |
| Cacheable | No |
| Allowed in HTML forms | No |

Syntax
------

```http
OPTIONS /index.html HTTP/1.1
OPTIONS * HTTP/1.1
```

Examples
--------

### Identifying allowed request methods

To find out which request methods a server supports, one can use the `curl` command-line program to issue an `OPTIONS` request:

```bash
curl -X OPTIONS https://example.org -i
```

The response then contains an `Allow` header that holds the allowed methods:

```http
HTTP/1.1 204 No Content
Allow: OPTIONS, GET, HEAD, POST
Cache-Control: max-age=604800
Date: Thu, 13 Oct 2016 11:45:00 GMT
Server: EOS (lax004/2813)
```

### Preflighted requests in CORS

In CORS, a preflight request is sent with the `OPTIONS` method so that the server can respond if it is acceptable to send the request. In this example, we will request permission for these parameters:

* The `Access-Control-Request-Method` header sent in the preflight request tells the server that when the actual request is sent, it will have a `POST` request method.
* The `Access-Control-Request-Headers` header tells the server that when the actual request is sent, it will have the `X-PINGOTHER` and `Content-Type` headers.

```http
OPTIONS /resources/post-here/ HTTP/1.1
Host: bar.example
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,\*/\*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Connection: keep-alive
Origin: https://foo.example
Access-Control-Request-Method: POST
Access-Control-Request-Headers: X-PINGOTHER, Content-Type
```

The server now can respond if it will accept a request under these circumstances. In this example, the server response says that:

`Access-Control-Allow-Origin`

The `https://foo.example` origin is permitted to request the `bar.example/resources/post-here/` URL via the following:

`Access-Control-Allow-Methods`

`POST`, `GET`, and `OPTIONS` are permitted methods for the URL. (This header is similar to the `Allow` response header, but used only for CORS.)

`Access-Control-Allow-Headers`

`X-PINGOTHER` and `Content-Type` are permitted request headers for the URL.

`Access-Control-Max-Age`

The above permissions may be cached for 86,400 seconds (1 day).

```http
HTTP/1.1 200 OK
Date: Mon, 01 Dec 2008 01:15:39 GMT
Server: Apache/2.0.61 (Unix)
Access-Control-Allow-Origin: https://foo.example
Access-Control-Allow-Methods: POST, GET, OPTIONS
Access-Control-Allow-Headers: X-PINGOTHER, Content-Type
Access-Control-Max-Age: 86400
Vary: Accept-Encoding, Origin
Keep-Alive: timeout=2, max=100
Connection: Keep-Alive
```

Status Code
-----------

Both `200` OK and `204` No Content are permitted status codes, but some browsers incorrectly believe `204 No Content` applies to the resource and do not send the subsequent request to fetch it.

Specifications
--------------

| Specification |
| --- |
| HTTP Semantics # OPTIONS |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Allow` header
* CORS


CSP errors and warnings (Content Security Policy) - HTTP

CSP errors and warnings (Content Security Policy)
=================================================

When you see any of the following messages logged in the browser devtools console, it indicates that a problem related to CSP has occurred.

* The page's settings blocked the loading of a resource: %1$S
* The page's settings blocked the loading of a resource at %2$S ("%1$S").
* A violation occurred for a report-only CSP policy ("%1$S"). The behavior was allowed, and a CSP report was sent.
* The page's settings observed the loading of a resource at %2$S ("%1$S"). A CSP report is being sent.
* Tried to send report to invalid URI: "%1$S"
* Couldn't parse report URI: %1$S
* Couldn't process unknown directive '%1$S'
* Ignoring unknown option %1$S
* Ignoring duplicate source %1$S
* Ignoring source '%1$S' (Not supported when delivered via meta element).
* Ignoring "%1$S" within script-src or style-src: nonce-source or hash-source specified
* Ignoring "%1$S" within script-src: 'strict-dynamic' specified
* Ignoring source "%1$S" (Only supported within script-src).
* Keyword 'strict-dynamic' within "%1$S" with no valid nonce or hash might block all scripts from loading
* The report URI (%1$S) should be an HTTP or HTTPS URI.
* This site (%1$S) has a Report-Only policy without a report URI. CSP will not block and cannot report violations of this policy.
* Failed to parse unrecognized source %1$S
* An attempt to execute inline scripts has been blocked
* An attempt to apply inline style sheets has been blocked
* An attempt to call JavaScript from a string (by calling a function like eval) has been blocked
* Upgrading insecure request '%1$S' to use '%2$S'
* Ignoring srcs for directive '%1$S'
* Interpreting %1$S as a hostname, not a keyword. If you intended this to be a keyword, use '%2$S' (wrapped in single quotes).
* Not supporting directive '%1$S'. Directive and values will be ignored.
* Blocking insecure request '%1$S'.(/en-US/docs/Web/HTTP/CSP/Errors/blockAllMixedContent)
* Ignoring '%1$S' since it does not contain any parameters.
* Ignoring sandbox directive when delivered in a report-only policy '%1$S'
* Referrer Directive '%1$S' has been deprecated. Please use the Referrer-Policy header instead.
* Ignoring '%1$S' because of '%2$S' directive.
* Couldn't parse invalid source %1$S
* Couldn't parse invalid host %1$S
* Couldn't parse scheme in %1$S
* Couldn't parse port in %1$S
* Duplicate %1$S directives detected. All but the first instance will be ignored.
* Directive '%1$S' has been deprecated. Please use directive 'worker-src' to control workers, or directive 'frame-src' to control frames respectively.
* Couldn't parse invalid sandbox flag '%1$S'


Content Security Policy: The page's settings blocked the loading of a resource: xyz - HTTP

Content Security Policy: The page's settings blocked the loading of a resource: xyz
===================================================================================

The warning "Content Security Policy: The page's settings blocked the loading of a resource: xyz" occurs when the page's CSP configuration given by `xyz` prevents the resource from being loaded into the document's context.

Message
-------

### Firefox

`Content Security Policy: The pages settings blocked the loading of a resource: xyz`

with:

`xyz`

The name of the CSP directive that blocked the resource. This may be expressed as either just the name of the directive, or as the entire policy directive string.

`uvw`

Text that provides information that may help you resolve the problem, potentially including specific changes you might make to the CSP configuration.

### Chrome

* `Refused to apply inline style because it violates the following Content Security Policy Directive: "xyz". uvw.`
* `Refused to execute inline script because it violates the following Content Security Policy directive: "xyz". uvw.`
* `Refused to run the JavaScript URL because it violates the following Content Security Policy directive: "xyz". uvw.`
* `Refused to execute inline event handler because it violates the following Content Security Policy directive: "xyz". uvw.`

with:

`xyz`

The name of the CSP directive that blocked the resource. This may be expressed as either just the name of the directive, or as the entire policy directive string.

`uvw`

Text that provides information that may help you resolve the problem, potentially including specific changes you might make to the CSP configuration.

What went wrong?
----------------

This warning message means that due to the existence of a particular CSP directive, a resource wasn't loaded.

See also
--------

* CSP errors and warnings
* Content Security Policy
* `Content-Security-Policy`
* `Content-Security-Policy-Report-Only`


Resource URLs - HTTP

Resource URLs
=============

**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

 Resource URLs, URLs prefixed with the `resource:` scheme, are used by
 Firefox and Firefox browser extensions to load resources internally, but some of the
 information is available to sites the browser connects to as well.

Syntax
------

 Resource URLs are composed of two parts: a prefix (`resource:`), and a URL
 pointing to the resource you want to load:

```url
resource://<url>
```

An example:

```url
resource://gre/res/svg.css
```

 When arrows are found in the resource URL's ('->'), it means that the first file
 loaded the next one:

```url
resource://<File-loader> -> <File-loaded>
```

Please refer to Identifying resources on the web for more general details.

 In this article, we focus on resource URIs, which are used internally by Firefox to
 point to built-in resources.

Threats
-------

 Because some of the information shared by `resource:` URLs is available to
 websites, a web page could run internal scripts and inspect internal resources of
 Firefox, including the default preferences, which could be a serious security and
 privacy issue.

 For example, a script on Browserleaks highlights what Firefox reveals when queried by a simple script
 running on the site (you can find the code in https://browserleaks.com/firefox#more).

 The file firefox.js passes preference names and values to the pref() function. For
 example:

```url
http://searchfox.org/mozilla-central/rev/48ea452803907f2575d81021e8678634e8067fc2/browser/app/profile/firefox.js#575
```

 Websites can easily collect Firefox default preferences by overriding this
 `pref()` function and using the script
 `resource:///defaults/preferences/firefox.js`.

 Furthermore, some default values of preferences differ between build configurations,
 such as platform and locale, which means websites could identify individual users using
 this information.

Solution
--------

 In order to fix this problem, Mozilla changed the behavior of loading resource: URIs in
 Firefox bug 863246, which landed in Firefox 57 (Quantum).

 In the past, web content was able to access whatever `resource:` URIs were
 desired — not only Firefox's internal resources, but also extensions' assets. Now this
 behavior is prohibited by default.

 It is however still necessary for Firefox to load resources in web content under
 certain circumstances. For example, if you open the view source page (View Page Source
 or View Selection Source), you will find it requires `viewsource.css` through
 a `resource:` URI. Resources that have to be exposed to web content have
 been moved to a new location named `resource://content-accessible/`, which is
 isolated and only contains non-sensitive resources. In this way we can keep essential
 resources exposed and have most threats eliminated.

**Note:** It is recommended that web and extension developers don't try
 to use resource URLs anymore. Their usage was hacky at best, and most usage won't work
 any more.

Specifications
--------------

resource: is not defined in any specification.

Browser compatibility
---------------------

resource: is Firefox only.

See also
--------

* Identifying resources on the Web
* What is a URL?
* IANA list of URI schemes (`resource:` is covered here)


Identifying resources on the Web - HTTP

Identifying resources on the Web
================================

The target of an HTTP request is called a "resource", whose nature isn't defined further; it can be a document, a photo, or anything else. Each resource is identified by a Uniform Resource Identifier (URI) used throughout HTTP for identifying resources.

URLs and URNs
-------------

### URLs

The most common form of URI is the Uniform Resource Locator (URL), which is known as the *web address*.

```url
https://developer.mozilla.org
https://developer.mozilla.org/en-US/docs/Learn/
https://developer.mozilla.org/en-US/search?q=URL
```

Any of those URLs can be typed into your browser's address bar to tell it to load the associated page (resource).

A URL is composed of different parts, some mandatory and others optional. A more complex example might look like this:

```url
http://www.example.com:80/path/to/myfile.html?key1=value1&key2=value2#SomewhereInTheDocument
```

### URNs

A Uniform Resource Name (URN) is a URI that identifies a resource by name in a particular namespace.

```url
urn:isbn:9780141036144
urn:ietf:rfc:7230
```

The two URNs correspond to

* the book Nineteen Eighty-Four by George Orwell,
* the IETF specification 7230, Hypertext Transfer Protocol (HTTP/1.1): Message Syntax and Routing.
Syntax of Uniform Resource Identifiers (URIs)
---------------------------------------------

### Scheme or protocol

![Protocol](/en-US/docs/Web/HTTP/Basics_of_HTTP/Identifying_resources_on_the_Web/mdn-url-protocol@x2.png)

`http://` is the protocol. It indicates which protocol the browser must use. Usually it is the HTTP protocol or its secured version, HTTPS. The Web requires one of these two, but browsers also know how to handle other protocols such as `mailto:` (to open a mail client) or `ftp:` to handle a file transfer, so don't be surprised if you see such protocols. Common schemes are:

| Scheme | Description |
| --- | --- |
| data | Data URLs |
| file | Host-specific file names |
| ftp | File Transfer Protocol |
| http/https | Hyper text transfer protocol (Secure) |
| javascript | URL-embedded JavaScript code |
| mailto | Electronic mail address |
| ssh | Secure shell |
| tel | telephone |
| urn | Uniform Resource Names |
| view-source | Source code of the resource |
| ws/wss | WebSocket connections (Secure) |

### Authority

![Domaine Name](/en-US/docs/Web/HTTP/Basics_of_HTTP/Identifying_resources_on_the_Web/mdn-url-domain@x2.png)

`www.example.com` is the domain name or authority that governs the namespace. It indicates which Web server is being requested. Alternatively, it is possible to directly use an IP address, but because it is less convenient, it is not often used on the Web.

### Port

![Port](/en-US/docs/Web/HTTP/Basics_of_HTTP/Identifying_resources_on_the_Web/mdn-url-port@x2.png)

`:80` is the port in this instance. It indicates the technical "gate" used to access the resources on the web server. It is usually omitted if the web server uses the standard ports of the HTTP protocol (80 for HTTP and 443 for HTTPS) to grant access to its resources. Otherwise, it is mandatory.

### Path

![Path to the file](/en-US/docs/Web/HTTP/Basics_of_HTTP/Identifying_resources_on_the_Web/mdn-url-path@x2.png)

`/path/to/myfile.html` is the path to the resource on the Web server. In the early days of the Web, a path like this represented a physical file location on the Web server. Nowadays, it is mostly an abstraction handled by Web servers without any physical reality.

### Query

![Parameters](/en-US/docs/Web/HTTP/Basics_of_HTTP/Identifying_resources_on_the_Web/mdn-url-parameters@x2.png)

`?key1=value1&key2=value2` are extra parameters provided to the Web server. Those parameters are a list of key/value pairs separated with the `&` symbol. The Web server can use those parameters to do extra stuff before returning the resource to the user. Each Web server has its own rules regarding parameters, and the only reliable way to know how a specific Web server is handling parameters is by asking the Web server owner.

### Fragment

![Anchor](/en-US/docs/Web/HTTP/Basics_of_HTTP/Identifying_resources_on_the_Web/mdn-url-anchor@x2.png)

`#SomewhereInTheDocument` is an anchor to another part of the resource itself. An anchor represents a sort of "bookmark" inside the resource, giving the browser the directions to show the content located at that "bookmarked" spot. On an HTML document, for example, the browser will scroll to the point where the anchor is defined; on a video or audio document, the browser will try to go to the time the anchor represents. It is worth noting that the part after the #, also known as the fragment identifier, is never sent to the server with the request.

Usage notes
-----------

When using URLs in HTML content, you should generally only use a few of these URL schemes. When referring to subresources — that is, files that are being loaded as part of a larger document — you should only use the HTTP and HTTPS schemes. Increasingly, browsers are removing support for using FTP to load subresources, for security reasons.

FTP is still acceptable at the top level (such as typed directly into the browser's URL bar, or the target of a link), although some browsers may delegate loading FTP content to another application.

Examples
--------

```url
https://developer.mozilla.org/en-US/docs/Learn
tel:+1-816-555-1212
git@github.com:mdn/browser-compat-data.git
ftp://example.org/resource.txt
urn:isbn:9780141036144
mailto:help@supercyberhelpdesk.info
```

Specifications
--------------

| Specification |
| --- |
| HTTP Semantics # uri |

See also
--------

* What is a URL?
* IANA list of URI schemes


Choosing between www and non-www URLs - HTTP

Choosing between www and non-www URLs
=====================================

A recurring question among website owners is whether to choose non-www or www URLs. This page provides some advice on what's best.

What are domain names?
----------------------

In an HTTP URL, the first substring that follows the initial `http://` or `https://` is called the domain name. This domain name is hosted on a server where the document resides.

A server isn't necessarily a physical machine: several servers can reside on the same physical machine. Or, one server can be handled by several machines, cooperating to produce the answer or balancing the load of the requests between them. The key point is that semantically *one domain name represents one single server*.

So, do I have to choose one or the other for my website?
--------------------------------------------------------

* **Yes**, you need to choose one and stick with it. The choice of which one to have as your canonical location is yours, but if you choose one, stick with it. It will make your website appear more consistent to your users and to search engines. This includes always linking to the chosen domain (which shouldn't be hard if you're using relative URLs in your website) and always sharing links (by email/social networks, etc.) to the same domain.
* **No**, you can have two. What is important is that you are coherent and consistent with which one is the official domain. **This official domain is called the *canonical* name.** All your absolute links should use it. But even so, you can still have the other domain working: HTTP allows two techniques so that it is clear for your users, or search engines, which domain is the canonical one, while still allowing the non-canonical domain to work and provide the expected pages.

So, choose one of your domains as your canonical one! There are two techniques below to allow the non-canonical domain to work still.

Techniques for canonical URLs
-----------------------------

There are different ways to choose which website is *canonical*.

### Using HTTP 301 redirects

In this case, you need to configure the server receiving the HTTP requests (which is most likely the same for www and non-www URLs) to respond with an adequate HTTP `301` response to any request to the non-canonical domain. This will redirect the browser trying to access the non-canonical URLs to their canonical equivalent. For example, if you've chosen to use non-www URLs as the canonical type, you should redirect all www URLs to their equivalent URL without the www.

Example:

1. A server receives a request for `http://www.example.org/whaddup` (when the canonical domain is example.org).
2. The server answers with a code `301` with the header ``Location`: http://example.org/whaddup`.
3. The client issues a request to the location under the canonical domain: `http://example.org/whaddup`.

The HTML5 boilerplate project has an example on how to configure an Apache server to redirect one domain to the other.

### Using <link rel="canonical">

It is possible to add a special HTML `<link>` element to a page to indicate what the canonical address of a page is. This has no impact on the human reader of the page, but tells search engine crawlers where the page actually lives. This way, search engines don't index the same page several times, potentially leading to it being considered as duplicate content or spam, and even removing or lowering your page from the search engine result pages.

When adding such a tag, you serve the same content for both domains, telling search engines which URL is canonical. In the previous example, `http://www.example.org/whaddup` would serve the same content as `http://example.org/whaddup`, but with an additional `<link>` element in the head:

```html
<link href="http://example.org/whaddup" rel="canonical" />
```

Unlike the previous case, browser history will consider non-www and www URLs as independent entries.

Make your page work for both
----------------------------

With these techniques, you can configure your server to respond correctly for both, the www-prefixed and the non-www-prefixed domains. It is good advice to do this since you can't predict which URL users will type in their browser's URL bar. It is a matter of choosing which type you want to use as your canonical location, then redirecting the other type to it.

Deciding the case
-----------------

This is a very subjective topic — it could be considered a bikeshedding issue. If you wish to read deeper, here are some resources:

* Options for bare domains on www.netlify.com (2020)
* WWW vs non-WWW – Which Is Better for WordPress SEO? on www.wpbeginner.com (2023)
See also
--------

* Stats on what people type in the URL bar (2011)


Evolution of HTTP - HTTP

Evolution of HTTP
=================

**HTTP** (HyperText Transfer Protocol) is the underlying protocol of the World Wide Web. Developed by Tim Berners-Lee and his team between 1989-1991, HTTP has gone through many changes that have helped maintain its simplicity while shaping its flexibility. Keep reading to learn how HTTP evolved from a protocol designed to exchange files in a semitrusted laboratory environment into a modern internet maze that carries images and videos in high resolution and 3D.

Invention of the World Wide Web
-------------------------------

In 1989, while working at CERN, Tim Berners-Lee wrote a proposal to build a hypertext system over the internet. Initially called the *Mesh*, it was later renamed the *World Wide Web* during its implementation in 1990. Built over the existing TCP and IP protocols, it consisted of 4 building blocks:

* A textual format to represent hypertext documents, the *HyperText Markup Language* (HTML).
* A simple protocol to exchange these documents, the *HyperText Transfer Protocol* (HTTP).
* A client to display (and edit) these documents, the first web browser called the *WorldWideWeb*.
* A server to give access to the document, an early version of *httpd*.

These four building blocks were completed by the end of 1990, and the first servers were running outside of CERN by early 1991. On August 6, 1991, Tim Berners-Lee posted on the public *alt.hypertext* newsgroup. This is now considered to be the official start of the World Wide Web as a public project.

The HTTP protocol used in those early phases was very simple. It was later dubbed HTTP/0.9 and is sometimes called the one-line protocol.

HTTP/0.9 – The one-line protocol
--------------------------------

The initial version of HTTP had no version number; it was later called 0.9 to differentiate it from later versions. HTTP/0.9 was extremely simple: requests consisted of a single line and started with the only possible method `GET` followed by the path to the resource. The full URL wasn't included as the protocol, server, and port weren't necessary once connected to the server.

```http
GET /mypage.html
```

The response was extremely simple, too: it only consisted of the file itself.

```html
<html>
  A very simple HTML page
</html>
```

Unlike subsequent evolutions, there were no HTTP headers. This meant that only HTML files could be transmitted. There were no status or error codes. If there was a problem, a specific HTML file was generated and included a description of the problem for human consumption.

HTTP/1.0 – Building extensibility
---------------------------------

HTTP/0.9 was very limited, but browsers and servers quickly made it more versatile:

* Versioning information was sent within each request (`HTTP/1.0` was appended to the `GET` line).
* A status code line was also sent at the beginning of a response. This allowed the browser itself to recognize the success or failure of a request and adapt its behavior accordingly. For example, updating or using its local cache in a specific way.
* The concept of HTTP headers was introduced for both requests and responses. Metadata could be transmitted and the protocol became extremely flexible and extensible.
* Documents other than plain HTML files could be transmitted thanks to the `Content-Type` header.

At this point in time, a typical request and response looked like this:

```http
GET /mypage.html HTTP/1.0
User-Agent: NCSA\_Mosaic/2.0 (Windows 3.1)

200 OK
Date: Tue, 15 Nov 1994 08:12:31 GMT
Server: CERN/3.0 libwww/2.17
Content-Type: text/html
<HTML>
A page with an image
 <IMG SRC="/myimage.gif">
</HTML>
```

It was followed by a second connection and a request to fetch the image (with the corresponding response):

```http
GET /myimage.gif HTTP/1.0
User-Agent: NCSA\_Mosaic/2.0 (Windows 3.1)

200 OK
Date: Tue, 15 Nov 1994 08:12:32 GMT
Server: CERN/3.0 libwww/2.17
Content-Type: text/gif
(image content)
```

Between 1991-1995, these were introduced with a try-and-see approach. A server and a browser would add a feature and see if it got traction. Interoperability problems were common. In an effort to solve these issues, an informational document that described the common practices was published in November 1996. This was known as RFC 1945 and defined HTTP/1.0.

HTTP/1.1 – The standardized protocol
------------------------------------

In the meantime, proper standardization was in progress. This happened in parallel to the diverse implementations of HTTP/1.0. The first standardized version of HTTP, HTTP/1.1, was published in early 1997, only a few months after HTTP/1.0.

HTTP/1.1 clarified ambiguities and introduced numerous improvements:

* A connection could be reused, which saved time. It no longer needed to be opened multiple times to display the resources embedded in the single original document.
* Pipelining was added. This allowed a second request to be sent before the answer to the first one was fully transmitted. This lowered the latency of the communication.
* Chunked responses were also supported.
* Additional cache control mechanisms were introduced.
* Content negotiation, including language, encoding, and type, was introduced. A client and a server could now agree on which content to exchange.
* Thanks to the `Host` header, the ability to host different domains from the same IP address allowed server collocation.

A typical flow of requests, all through one single connection, looked like this:

```http
GET /en-US/docs/Glossary/Simple\_header HTTP/1.1
Host: developer.mozilla.org
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:50.0) Gecko/20100101 Firefox/50.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,\*/\*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate, br
Referer: https://developer.mozilla.org/en-US/docs/Glossary/Simple\_header

200 OK
Connection: Keep-Alive
Content-Encoding: gzip
Content-Type: text/html; charset=utf-8
Date: Wed, 20 Jul 2016 10:55:30 GMT
Etag: "547fa7e369ef56031dd3bff2ace9fc0832eb251a"
Keep-Alive: timeout=5, max=1000
Last-Modified: Tue, 19 Jul 2016 00:59:33 GMT
Server: Apache
Transfer-Encoding: chunked
Vary: Cookie, Accept-Encoding

(content)

GET /static/img/header-background.png HTTP/1.1
Host: developer.mozilla.org
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:50.0) Gecko/20100101 Firefox/50.0
Accept: \*/\*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate, br
Referer: https://developer.mozilla.org/en-US/docs/Glossary/Simple\_header

200 OK
Age: 9578461
Cache-Control: public, max-age=315360000
Connection: keep-alive
Content-Length: 3077
Content-Type: image/png
Date: Thu, 31 Mar 2016 13:34:46 GMT
Last-Modified: Wed, 21 Oct 2015 18:27:50 GMT
Server: Apache

(image content of 3077 bytes)
```

HTTP/1.1 was first published as RFC 2068 in January 1997.

More than 15 years of extensions
--------------------------------

The extensibility of HTTP made it easy to create new headers and methods. Even though the HTTP/1.1 protocol was refined over two revisions, RFC 2616 published in June 1999 and RFC 7230-RFC 7235 published in June 2014 before the release of HTTP/2, it was extremely stable for more than 15 years.

### Using HTTP for secure transmissions

The largest change to HTTP was made at the end of 1994. Instead of sending HTTP over a basic TCP/IP stack, the computer-services company Netscape Communications created an additional encrypted transmission layer on top of it: SSL. SSL 1.0 was never released to the public, but SSL 2.0 and its successor SSL 3.0 allowed for the creation of e-commerce websites. To do this, they encrypted and guaranteed the authenticity of the messages exchanged between the server and client. SSL was eventually standardized and became TLS.

During the same time period, it became clear that an encrypted transport layer was needed. The web was no longer a mostly academic network, and instead became a jungle where advertisers, random individuals, and criminals competed for as much private data as possible. As the applications built over HTTP became more powerful and required access to private information like address books, email, and user location, TLS became necessary outside the e-commerce use case.

### Using HTTP for complex applications

Tim Berners-Lee didn't originally envision HTTP as a read-only medium. He wanted to create a web where people could add and move documents remotely—a kind of distributed file system. Around 1996, HTTP was extended to allow authoring, and a standard called WebDAV was created. It grew to include specific applications like CardDAV for handling address book entries and CalDAV for dealing with calendars. But all these \*DAV extensions had a flaw: they were only usable when implemented by the servers.

In 2000, a new pattern for using HTTP was designed: representational state transfer (or REST). The API wasn't based on the new HTTP methods, but instead relied on access to specific URIs with basic HTTP/1.1 methods. This allowed any web application to let an API retrieve and modify its data without having to update the browsers or the servers. All necessary information was embedded in the files that the websites served through standard HTTP/1.1. The drawback of the REST model was that each website defined its own nonstandard RESTful API and had total control of it. This differed from the \*DAV extensions where clients and servers were interoperable. RESTful APIs became very common in the 2010s.

Since 2005, more APIs have become available to web pages. Several of these APIs create extensions to the HTTP protocol for specific purposes:

* Server-sent events, where the server can push occasional messages to the browser.
* WebSocket, a new protocol that can be set up by upgrading an existing HTTP connection.
### Relaxing the security-model of the web

HTTP is independent of the web security model, known as the same-origin policy. In fact, the current web security model was developed after the creation of HTTP! Over the years, it proved useful to lift some restrictions of this policy under certain constraints. The server transmitted how much and when to lift such restrictions to the client using a new set of HTTP headers. These were defined in specifications like Cross-Origin Resource Sharing (CORS) and the Content Security Policy (CSP).

In addition to these large extensions, many other headers were added, sometimes only experimentally. Notable headers are the Do Not Track (`DNT`) header to control privacy, `X-Frame-Options`, and `Upgrade-Insecure-Requests` but many more exist.

HTTP/2 – A protocol for greater performance
-------------------------------------------

Over the years, web pages became more complex. Some of them were even applications in their own right. More visual media was displayed and the volume and size of scripts adding interactivity also increased. Much more data was transmitted over significantly more HTTP requests and this created more complexity and overhead for HTTP/1.1 connections. To account for this, Google implemented an experimental protocol SPDY in the early 2010s. This alternative way of exchanging data between client and server amassed interest from developers working on both browsers and servers. SPDY defined an increase in responsiveness and solved the problem of duplicate data transmission, serving as the foundation for the HTTP/2 protocol.

The HTTP/2 protocol differs from HTTP/1.1 in a few ways:

* It's a binary protocol rather than a text protocol. It can't be read and created manually. Despite this hurdle, it allows for the implementation of improved optimization techniques.
* It's a multiplexed protocol. Parallel requests can be made over the same connection, removing the constraints of the HTTP/1.x protocol.
* It compresses headers. As these are often similar among a set of requests, this removes the duplication and overhead of data transmitted.
* It allows a server to populate data in a client cache through a mechanism called the server push.

Officially standardized in May 2015, HTTP/2 use peaked in January 2022 at 46.9% of all websites (see these stats). High-traffic websites showed the most rapid adoption in an effort to save on data transfer overhead and subsequent budgets.

This rapid adoption was likely because HTTP/2 didn't require changes to websites and applications. To use it, only an up-to-date server that communicated with a recent browser was necessary. Only a limited set of groups was needed to trigger adoption, and as legacy browser and server versions were renewed, usage was naturally increased, without significant work for web developers.

Post-HTTP/2 evolution
---------------------

HTTP's extensibility is still being used to add new features. Notably, we can cite new extensions of the HTTP protocol that appeared in 2016:

* Support for `Alt-Svc` allowed the dissociation of the identification and the location of a given resource. This meant a smarter CDN caching mechanism.
* The introduction of client hints allowed the browser or client to proactively communicate information about its requirements and hardware constraints to the server.
* The introduction of security-related prefixes in the `Cookie` header helped guarantee that secure cookies couldn't be altered.
HTTP/3 - HTTP over QUIC
-----------------------

The next major version of HTTP, HTTP/3 has the same semantics as earlier versions of HTTP but uses QUIC instead of TCP for the transport layer portion. By October 2022, 26% of all websites were using HTTP/3.

QUIC is designed to provide much lower latency for HTTP connections. Like HTTP/2, it is a multiplexed protocol, but HTTP/2 runs over a single TCP connection, so packet loss detection and retransmission handled at the TCP layer can block all streams. QUIC runs multiple streams over UDP and implements packet loss detection and retransmission independently for each stream, so that if an error occurs, only the stream with data in that packet is blocked.

Defined in RFC 9114, HTTP/3 is supported by most major browsers including Chromium (and its variants such as Chrome and Edge) and Firefox.


MIME types (IANA media types) - HTTP

MIME types (IANA media types)
=============================

 A **media type** (also known as a **Multipurpose Internet Mail Extensions or MIME type**) indicates the nature and format of a document, file, or assortment of bytes.
 MIME types are defined and standardized in IETF's RFC 6838.

The Internet Assigned Numbers Authority (IANA) is responsible for all official MIME types, and you can find the most up-to-date and complete list at their Media Types page.

**Warning:** Browsers use the MIME type, *not the file extension*, to determine how to process a URL,
 so it's important that web servers send the correct MIME type in the response's `Content-Type` header.
 If this is not correctly configured, browsers are likely to misinterpret the contents of files, sites will not work correctly, and downloaded files may be mishandled.

Structure of a MIME type
------------------------

A MIME type most commonly consists of just two parts: a *type* and a *subtype*, separated by a slash (`/`) — with no whitespace between:
```

type/subtype
```

The ***type*** represents the general category into which the data type falls, such as `video` or `text`.

 The ***subtype*** identifies the exact kind of data of the specified type the MIME type represents.
 For example, for the MIME type `text`, the subtype might be `plain` (plain text), `html` (HTML source code), or `calendar` (for iCalendar/`.ics`) files.

Each type has its own set of possible subtypes. A MIME type always has both a type and a subtype, never just one or the other.

An optional **parameter** can be added to provide additional details:
```

type/subtype;parameter=value
```

 For example, for any MIME type whose main type is `text`, you can add the optional `charset` parameter to specify the character set used for the
 characters in the data.
 If no `charset` is specified, the default is ASCII (`US-ASCII`) unless overridden by the user agent's settings.
 To specify a UTF-8 text file, the MIME type `text/plain;charset=UTF-8` is used.

MIME types are case-insensitive but are traditionally written in lowercase. The parameter values can be case-sensitive.

### Types

 There are two classes of type: **discrete** and **multipart**.
 Discrete types are types which represent a single file or medium, such as a single text or music file, or a single video.
 A multipart type represents a document that's comprised of multiple component parts, each of which may have its own individual MIME type; or, a multipart type may encapsulate multiple files being sent together in one transaction.
 For example, multipart MIME types are used when attaching multiple files to an email.

#### Discrete types

The discrete types currently registered with the IANA are:

`application`

 Any kind of binary data that doesn't fall explicitly into one of the other types;
 either data that will be executed or interpreted in some way or binary data that requires a specific application or category of application to use.
 Generic binary data (or binary data whose true type is unknown) is `application/octet-stream`.
 Other common examples include `application/pdf`, `application/pkcs8`, and `application/zip`.
 (See application type registry at IANA)

`audio`

 Audio or music data. Examples include `audio/mpeg`,
 `audio/vorbis`.
 (See audio type registry at IANA)

`example`

 Reserved for use as a placeholder in examples showing how to use MIME types.
 These should never be used outside of sample code listings and documentation.
 `example` can also be used as a subtype;
 for instance, in an example related to working with audio on the web, the MIME type `audio/example` can be used to indicate that the type is a placeholder and should be replaced with an appropriate one when using the code in the real world.

`font`

 Font/typeface data. Common examples include `font/woff`, `font/ttf`, and `font/otf`.
 (See font type registry at IANA)

`image`

 Image or graphical data including both bitmap and vector still images as well as
 animated versions of still image formats such as animated GIF or APNG.
 Common examples are `image/jpeg`, `image/png`, and `image/svg+xml`.
 (See image type registry at IANA)

`model`

 Model data for a 3D object or scene. Examples include `model/3mf` and `model/vrml`.
 (See model type registry at IANA)

`text`

 Text-only data including any human-readable content, source code, or textual data such as comma-separated value (CSV) formatted data.
 Examples include: `text/plain`, `text/csv`, and `text/html`.
 (See text type registry at IANA)

`video`

 Video data or files, such as MP4 movies (`video/mp4`).
 (See video type registry at IANA)

 For text documents without a specific subtype, `text/plain` should be used.
 Similarly, for binary documents without a specific or known subtype, `application/octet-stream` should be used.

#### Multipart types

**Multipart** types indicate a category of document broken into
 pieces, often with different MIME types; they can also be used — especially in email
 scenarios — to represent multiple, separate files which are all part of the same
 transaction. They represent a **composite document**.

 Except for `multipart/form-data`, used in the `POST` method of HTML Forms, and `multipart/byteranges`, used with `206` `Partial Content` to send part of a document, HTTP doesn't handle multipart documents in a special way: the message is transmitted to the browser (which will likely
 show a "Save As" window if it doesn't know how to display the document).

There are two multipart types:

`message`

 A message that encapsulates other messages. This can be used, for instance, to represent an email that includes a forwarded message as part of its data,
 or to allow sending very large messages in chunks as if it were multiple messages.
 Examples include `message/rfc822` (for forwarded or replied-to message quoting) and `message/partial` to allow breaking a large message into smaller ones automatically to be reassembled by the recipient.
 (See message type registry at IANA)

`multipart`

 Data that consists of multiple components which may individually have different MIME types.
 Examples include `multipart/form-data` (for data produced using the `FormData` API) and `multipart/byteranges` (defined in RFC 7233, section 5.4.1 and used with HTTP's `206`
 "Partial Content" response returned when the fetched data is only part of the content, such as is delivered using the `Range` header).
 (See multipart type registry at IANA)

Important MIME types for Web developers
---------------------------------------

### application/octet-stream

This is the default for binary files. As it means *unknown binary* file, browsers usually don't execute it, or even ask if it should be executed. They treat it as if the `Content-Disposition` header was set to `attachment`, and propose a "Save As" dialog.

### text/plain

This is the default for textual files. Even if it really means "unknown textual file," browsers assume they can display it.

**Note:** `text/plain` does not mean "any kind of textual data."
 If they expect a specific kind of textual data, they will likely not consider it a match.
 Specifically if they download a `text/plain` file from a `<link>` element declaring a CSS file, they will not recognize it as a valid CSS file if presented with `text/plain`.
 The CSS mime type `text/css` must be used.

### text/css

 CSS files used to style a Web page **must** be sent with `text/css`.
 If a server doesn't recognize the `.css` suffix for CSS files, it may send them with `text/plain` or `application/octet-stream` MIME types.
 If so, they won't be recognized as CSS by most browsers and will be ignored.

### text/html

All HTML content should be served with this type. Alternative MIME types for XHTML (like `application/xhtml+xml`) are mostly useless nowadays.

**Note:** Use `application/xml` or `application/xhtml+xml` if you want XML's strict parsing rules, `<![CDATA[…]]>` sections, or elements that aren't from HTML/SVG/MathML namespaces.

### text/javascript

 Per the IANA Media Types registry, RFC 9239, and the HTML specification, JavaScript content should always be served using the MIME type `text/javascript`.
 No other MIME types are considered valid for JavaScript, and using any MIME type other than `text/javascript` may result in scripts that do not load or run.

 You may find some JavaScript content incorrectly served with a `charset` parameter as part of the MIME type — as an attempt to specify the character set for the script content.
 That `charset` parameter isn't valid for JavaScript content, and in most cases will result in a script failing to load.

#### Legacy JavaScript MIME types

 In addition to the `text/javascript` MIME type, for historical reasons, the MIME Sniffing Standard
 (the definition of how browsers should interpret MIME types and figure
 out what to do with content that doesn't have a valid one) also allows JavaScript to be served using any of the following legacy JavaScript MIME types:

* `application/javascript`
Deprecated
* `application/ecmascript`
Deprecated
* `application/x-ecmascript`
Non-standard
* `application/x-javascript`
Non-standard
* `text/ecmascript`
Deprecated
* `text/javascript1.0`
Non-standard
* `text/javascript1.1`
Non-standard
* `text/javascript1.2`
Non-standard
* `text/javascript1.3`
Non-standard
* `text/javascript1.4`
Non-standard
* `text/javascript1.5`
Non-standard
* `text/jscript`
Non-standard
* `text/livescript`
Non-standard
* `text/x-ecmascript`
Non-standard
* `text/x-javascript`
Non-standard

**Note:** Even though any given user agent may support any or all of these, you should only use `text/javascript`.
 It's the only MIME type guaranteed to work now and into the future.

### Image types

 Files whose MIME type is `image` contain image data.
 The subtype specifies which specific image file format the data represents.

The following image types are used commonly enough to be considered *safe* for use on web pages:

* `image/apng`: Animated Portable Network Graphics (APNG)
* `image/avif` : AV1 Image File Format (AVIF)
* `image/gif`: Graphics Interchange Format (GIF)
* `image/jpeg`: Joint Photographic Expert Group image (JPEG)
* `image/png`: Portable Network Graphics (PNG)
* `image/svg+xml`: Scalable Vector Graphics (SVG)
* `image/webp`: Web Picture format (WEBP)

The Image file type and format guide provides information and recommendations about when to use the different image formats.

### Audio and video types

As is the case for images, HTML doesn't mandate that web browsers support any specific file and codec types for the `<audio>` and `<video>` elements, so it's important to consider your target audience and the range of browsers (and versions of those browsers) they may be using when choosing the file type and codecs to use for media.

 Our media container formats guide provides a list of the file types that are commonly supported by web browsers,
 including information about what their special use cases may be, any drawbacks they have, and compatibility information, along with other details.

 The audio codec and video codec guides list the various codecs that web browsers often support, providing compatibility details along with technical information such as how many audio channels they support, what sort of compression is used, and what bit rates and so forth they're useful at.
 The codecs used by WebRTC guide expands upon this by specifically covering the codecs supported by the major web browsers, so you can choose the codecs that best cover the range of browsers you wish to support.

 As for MIME types of audio or video files, they typically specify the container format (file type).
 The optional codecs parameter can be added to the MIME type to further specify which codecs to use and what options were used to encode the media, such as codec profile, level, or other such information.

For more information on common media types, see the Common MIME types page.

### multipart/form-data

The `multipart/form-data` type can be used when sending the values of a completed HTML Form from browser to server.

 As a multipart document format, it consists of different parts, delimited by a boundary (a string starting with a double dash `--`).
 Each part is its own entity with its own HTTP headers, `Content-Disposition`, and `Content-Type` for file uploading fields.

```http
Content-Type: multipart/form-data; boundary=aBoundaryString
(other headers associated with the multipart document as a whole)

--aBoundaryString
Content-Disposition: form-data; name="myFile"; filename="img.jpg"
Content-Type: image/jpeg

(data)
--aBoundaryString
Content-Disposition: form-data; name="myField"

(data)
--aBoundaryString
(more subparts)
--aBoundaryString--
```

The following `<form>`:

```html
<form
 action="http://localhost:8000/"
 method="post"
 enctype="multipart/form-data">
  <label>Name: <input name="myTextField" value="Test" /></label>
  <label><input type="checkbox" name="myCheckBox" /> Check</label>
  <label>
    Upload file: <input type="file" name="myFile" value="test.txt" />
  </label>
  <button>Send the file</button>
</form>
```

will send this message:

```http
POST / HTTP/1.1
Host: localhost:8000
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:50.0) Gecko/20100101 Firefox/50.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,\*/\*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: keep-alive
Upgrade-Insecure-Requests: 1
Content-Type: multipart/form-data; boundary=---------------------------8721656041911415653955004498
Content-Length: 465

-----------------------------8721656041911415653955004498
Content-Disposition: form-data; name="myTextField"

Test
-----------------------------8721656041911415653955004498
Content-Disposition: form-data; name="myCheckBox"

on
-----------------------------8721656041911415653955004498
Content-Disposition: form-data; name="myFile"; filename="test.txt"
Content-Type: text/plain

Simple file.
-----------------------------8721656041911415653955004498--
```

### multipart/byteranges

The `multipart/byteranges` MIME type is used to send partial responses to the browser.

 When the `206 Partial Content` status code is sent, this MIME type indicates that the document is composed of several parts, one for each of the
 requested ranges. Like other multipart types, the `Content-Type` uses a `boundary` to separate the pieces.
 Each piece has a `Content-Type` header with its actual type and a `Content-Range` of the range it represents.

```http
HTTP/1.1 206 Partial Content
Accept-Ranges: bytes
Content-Type: multipart/byteranges; boundary=3d6b6a416f9b5
Content-Length: 385

--3d6b6a416f9b5
Content-Type: text/html
Content-Range: bytes 100-200/1270

eta http-equiv="Content-type" content="text/html; charset=utf-8" />
 <meta name="viewport" content
--3d6b6a416f9b5
Content-Type: text/html
Content-Range: bytes 300-400/1270

-color: #f0f0f2;
 margin: 0;
 padding: 0;
 font-family: "Open Sans", "Helvetica
--3d6b6a416f9b5--
```

Importance of setting the correct MIME type
-------------------------------------------

 Most web servers send unrecognized resources as the `application/octet-stream` MIME type.
 For security reasons, most browsers do not allow setting a custom default action for such resources, forcing the user to save it to disk to use it.

Some common incorrect server configurations:

* RAR-compressed files.
 In this case, the ideal would be the true type of the original files; this is often impossible as .RAR files can hold several resources of different types.
 In this case, configure the server to send `application/x-rar-compressed`.
* Audio and video.
 Only resources with the correct MIME Type will be played in `<video>` or `<audio>` elements.
 Be sure to specify the correct media type for audio and video.
* Proprietary file types.
 Avoid using `application/octet-stream` as most browsers do not allow defining a default behavior (like "Open in Word") for this generic MIME type.
 A specific type like `application/vnd.mspowerpoint` lets users open such files automatically in the presentation software of their choice.
MIME sniffing
-------------

In the absence of a MIME type, or in certain cases where browsers believe they are incorrect, browsers may perform *MIME sniffing* — guessing the correct MIME type by looking at the bytes of the resource.

 Each browser performs MIME sniffing differently and under different circumstances.
 (For example, Safari will look at the file extension in the URL if the sent MIME type is unsuitable.)
 There are security concerns as some MIME types represent executable content.
 Servers can prevent MIME sniffing by sending the `X-Content-Type-Options` header.

Other methods of conveying document type
----------------------------------------

MIME types are not the only way to convey document type information:

* Filename suffixes are sometimes used, especially on Microsoft Windows.
 Not all operating systems consider these suffixes meaningful (such as Linux and macOS), and there is no guarantee they are correct.
* Magic numbers. The syntax of different formats allows file-type inference by looking at their byte structure.
 For example, GIF files start with the `47 49 46 38 39` hexadecimal value (`GIF89`), and PNG files with `89 50 4E 47` (`.PNG`).
 Not all file types have magic numbers, so this is not 100% reliable either.
See also
--------

* Web media technologies
* Guide to media types used on the web
* Properly configuring server MIME types


Data URLs - HTTP

Data URLs
=========

**Data URLs**, URLs prefixed with the `data:` scheme, allow content creators to embed small files inline in documents. They were formerly known as "data URIs" until that name was retired by the WHATWG.

**Note:** Data URLs are treated as unique opaque origins by modern browsers, rather than inheriting the origin of the settings object responsible for the navigation.

Syntax
------

Data URLs are composed of four parts: a prefix (`data:`), a MIME type indicating the type of data, an optional `base64` token if non-textual, and the data itself:
```

data:[<mediatype>][;base64],<data>
```

The `mediatype` is a MIME type string, such as `'image/jpeg'` for a JPEG image file. If omitted, defaults to `text/plain;charset=US-ASCII`

If the data contains characters defined in RFC 3986 as reserved characters, or contains space characters, newline characters, or other non-printing characters, those characters must be URL encoded.

If the data is textual, you can embed the text (using the appropriate entities or escapes based on the enclosing document's type). Otherwise, you can specify `base64` to embed base64-encoded binary data. You can find more info on MIME types here and here.

A few examples:

`data:,Hello%2C%20World%21`

The text/plain data `Hello, World!`. Note how the comma is URl encoded as `%2C`, and the space character as `%20`.

`data:text/plain;base64,SGVsbG8sIFdvcmxkIQ==`

base64-encoded version of the above

`data:text/html,%3Ch1%3EHello%2C%20World%21%3C%2Fh1%3E`

An HTML document with `<h1>Hello, World!</h1>`

`data:text/html,%3Cscript%3Ealert%28%27hi%27%29%3B%3C%2Fscript%3E`

An HTML document with `<script>alert('hi');</script>` that executes a JavaScript alert. Note that the closing script tag is required.

Encoding data into base64 format
--------------------------------

Base64 is a group of binary-to-text encoding schemes that represent binary data in an ASCII string format by translating it into a radix-64 representation. By consisting only of ASCII characters, base64 strings are generally url-safe, and that's why they can be used to encode data in Data URLs.

### Encoding in JavaScript

The Web APIs have native methods to encode or decode to base64: Base64.

### Encoding on a Unix system

Base64 encoding of a file or string on Linux and macOS systems can be achieved using the command-line `base64` (or, as an alternative, the `uuencode` utility with `-m` argument).

```bash
echo -n hello|base64
# outputs to console: aGVsbG8=

echo -n hello>a.txt
base64 a.txt
# outputs to console: aGVsbG8=

base64 a.txt>b.txt
# outputs to file b.txt: aGVsbG8=
```

### Encoding on Microsoft Windows

On Windows, Convert.ToBase64String from PowerShell can be used to perform the Base64 encoding:
```

[convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes("hello"))
# outputs to console: aGVsbG8=
```

Alternatively, a GNU/Linux shell (such as WSL) provides the utility `base64`:

```bash
bash$ echo -n hello | base64
# outputs to console: aGVsbG8=
```

Common problems
---------------

This section describes problems that commonly occur when creating and using `data` URLs.

```html
data:text/html,lots of text…<p><a name%3D"bottom">bottom</a>?arg=val</p>
```

This represents an HTML resource whose contents are:

```html
lots of text…
<p><a name="bottom">bottom</a>?arg=val</p>
```

Syntax

The format for `data` URLs is very simple, but it's easy to forget to put a comma before the "data" segment, or to incorrectly encode the data into base64 format.

Formatting in HTML

A `data` URL provides a file within a file, which can potentially be very wide relative to the width of the enclosing document. As a URL, the `data` should be formattable with whitespace (linefeed, tab, or spaces), but there are practical issues that arise when using base64 encoding.

Length limitations

Browsers are not required to support any particular maximum length of data. For example, the Opera 11 browser limited URLs to 65535 characters long which limits `data` URLs to 65529 characters (65529 characters being the length of the encoded data, not the source, if you use the plain `data:`, without specifying a MIME type). Firefox version 97 and newer supports `data` URLs of up to 32MB (before 97 the limit was close to 256MB). Chromium objects to URLs over 512MB, and Webkit (Safari) to URLs over 2048MB.

Lack of error handling

Invalid parameters in media, or typos when specifying `'base64'`, are ignored, but no error is provided.

No support for query strings, etc.

The data portion of a data URL is opaque, so an attempt to use a query string (page-specific parameters, with the syntax `<url>?parameter-data`) with a data URL will just include the query string in the data the URL represents.

Security issues

A number of security issues (for example, phishing) have been associated with data URLs, and navigating to them in the browser's top level. To mitigate such issues, top-level navigation to `data:` URLs is blocked in all modern browsers. See this blog post from the Mozilla Security Team for more details.

Specifications
--------------

| Specification |
| --- |
| The "data" URL scheme # section-2 |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Base64
* URL encoding
* `atob()`
* `btoa()`
* CSS `url()`
* URI


Common MIME types - HTTP

Common MIME types
=================

This topic lists the most common MIME types with corresponding document types, ordered by their common extensions.

The following two important MIME types are the default types:

* `text/plain` is the default value for textual files. A textual file should be human-readable and must not contain binary data.
* `application/octet-stream` is the default value for all other cases. An unknown file type should use this type. Browsers are particularly careful when manipulating these files to protect users from software vulnerabilities and possible dangerous behavior.

IANA is the official registry of MIME media types and maintains a list of all the official MIME types. This table lists important MIME types for the Web:

| Extension | Kind of document | MIME Type |
| --- | --- | --- |
| `.aac` | AAC audio | `audio/aac` |
| `.abw` | AbiWord document | `application/x-abiword` |
| `.apng` | Animated Portable Network Graphics (APNG) image | `image/apng` |
| `.arc` | Archive document (multiple files embedded) | `application/x-freearc` |
| `.avif` | AVIF image | `image/avif` |
| `.avi` | AVI: Audio Video Interleave | `video/x-msvideo` |
| `.azw` | Amazon Kindle eBook format | `application/vnd.amazon.ebook` |
| `.bin` | Any kind of binary data | `application/octet-stream` |
| `.bmp` | Windows OS/2 Bitmap Graphics | `image/bmp` |
| `.bz` | BZip archive | `application/x-bzip` |
| `.bz2` | BZip2 archive | `application/x-bzip2` |
| `.cda` | CD audio | `application/x-cdf` |
| `.csh` | C-Shell script | `application/x-csh` |
| `.css` | Cascading Style Sheets (CSS) | `text/css` |
| `.csv` | Comma-separated values (CSV) | `text/csv` |
| `.doc` | Microsoft Word | `application/msword` |
| `.docx` | Microsoft Word (OpenXML) | `application/vnd.openxmlformats-officedocument.wordprocessingml.document` |
| `.eot` | MS Embedded OpenType fonts | `application/vnd.ms-fontobject` |
| `.epub` | Electronic publication (EPUB) | `application/epub+zip` |
| `.gz` | GZip Compressed Archive | `application/gzip` |
| `.gif` | Graphics Interchange Format (GIF) | `image/gif` |
| `.htm`, `.html` | HyperText Markup Language (HTML) | `text/html` |
| `.ico` | Icon format | `image/vnd.microsoft.icon` |
| `.ics` | iCalendar format | `text/calendar` |
| `.jar` | Java Archive (JAR) | `application/java-archive` |
| `.jpeg`, `.jpg` | JPEG images | `image/jpeg` |
| `.js` | JavaScript | `text/javascript` (Specifications: HTML and RFC 9239) |
| `.json` | JSON format | `application/json` |
| `.jsonld` | JSON-LD format | `application/ld+json` |
| `.mid`, `.midi` | Musical Instrument Digital Interface (MIDI) | `audio/midi`, `audio/x-midi` |
| `.mjs` | JavaScript module | `text/javascript` |
| `.mp3` | MP3 audio | `audio/mpeg` |
| `.mp4` | MP4 video | `video/mp4` |
| `.mpeg` | MPEG Video | `video/mpeg` |
| `.mpkg` | Apple Installer Package | `application/vnd.apple.installer+xml` |
| `.odp` | OpenDocument presentation document | `application/vnd.oasis.opendocument.presentation` |
| `.ods` | OpenDocument spreadsheet document | `application/vnd.oasis.opendocument.spreadsheet` |
| `.odt` | OpenDocument text document | `application/vnd.oasis.opendocument.text` |
| `.oga` | OGG audio | `audio/ogg` |
| `.ogv` | OGG video | `video/ogg` |
| `.ogx` | OGG | `application/ogg` |
| `.opus` | Opus audio | `audio/opus` |
| `.otf` | OpenType font | `font/otf` |
| `.png` | Portable Network Graphics | `image/png` |
| `.pdf` | Adobe Portable Document Format (PDF) | `application/pdf` |
| `.php` | Hypertext Preprocessor (**Personal Home Page**) | `application/x-httpd-php` |
| `.ppt` | Microsoft PowerPoint | `application/vnd.ms-powerpoint` |
| `.pptx` | Microsoft PowerPoint (OpenXML) | `application/vnd.openxmlformats-officedocument.presentationml.presentation` |
| `.rar` | RAR archive | `application/vnd.rar` |
| `.rtf` | Rich Text Format (RTF) | `application/rtf` |
| `.sh` | Bourne shell script | `application/x-sh` |
| `.svg` | Scalable Vector Graphics (SVG) | `image/svg+xml` |
| `.tar` | Tape Archive (TAR) | `application/x-tar` |
| `.tif`, `.tiff` | Tagged Image File Format (TIFF) | `image/tiff` |
| `.ts` | MPEG transport stream | `video/mp2t` |
| `.ttf` | TrueType Font | `font/ttf` |
| `.txt` | Text, (generally ASCII or ISO 8859-*n*) | `text/plain` |
| `.vsd` | Microsoft Visio | `application/vnd.visio` |
| `.wav` | Waveform Audio Format | `audio/wav` |
| `.weba` | WEBM audio | `audio/webm` |
| `.webm` | WEBM video | `video/webm` |
| `.webp` | WEBP image | `image/webp` |
| `.woff` | Web Open Font Format (WOFF) | `font/woff` |
| `.woff2` | Web Open Font Format (WOFF) | `font/woff2` |
| `.xhtml` | XHTML | `application/xhtml+xml` |
| `.xls` | Microsoft Excel | `application/vnd.ms-excel` |
| `.xlsx` | Microsoft Excel (OpenXML) | `application/vnd.openxmlformats-officedocument.spreadsheetml.sheet` |
| `.xml` | XML | `application/xml` is recommended as of RFC 7303 (section 4.1), but `text/xml` is still used sometimes. You can assign a specific MIME type to a file with `.xml` extension depending on how its contents are meant to be interpreted. For instance, an Atom feed is `application/atom+xml`, but `application/xml` serves as a valid default. |
| `.xul` | XUL | `application/vnd.mozilla.xul+xml` |
| `.zip` | ZIP archive | `application/zip` |
| `.3gp` | 3GPP audio/video container | `video/3gpp`; `audio/3gpp` if it doesn't contain video |
| `.3g2` | 3GPP2 audio/video container | `video/3gpp2`; `audio/3gpp2` if it doesn't contain video |
| `.7z` | 7-zip archive | `application/x-7z-compressed` |


X-XSS-Protection - HTTP

X-XSS-Protection
================

**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

The HTTP **`X-XSS-Protection`** response header is a feature of Internet Explorer, Chrome and Safari that stops pages from loading when they detect reflected cross-site scripting (XSS) attacks. These protections are largely unnecessary in modern browsers when sites implement a strong `Content-Security-Policy` that disables the use of inline JavaScript (`'unsafe-inline'`).

**Warning:** Even though this feature can protect users of older web browsers that don't yet support CSP, in some cases, **XSS protection can create XSS vulnerabilities** in otherwise safe websites. See the section below for more information.

**Note:**

* Chrome has removed their XSS Auditor
* Firefox has not, and will not implement `X-XSS-Protection`
* Edge has retired their XSS filter

This means that if you do not need to support legacy browsers, it is recommended that you use `Content-Security-Policy` without allowing `unsafe-inline` scripts instead.

|  |  |
| --- | --- |
| Header type | Response header |
| Forbidden header name | no |

Syntax
------

```http
X-XSS-Protection: 0
X-XSS-Protection: 1
X-XSS-Protection: 1; mode=block
X-XSS-Protection: 1; report=<reporting-uri>
```

0

Disables XSS filtering.

1

Enables XSS filtering (usually default in browsers). If a cross-site scripting attack is detected, the browser will sanitize the page (remove the unsafe parts).

1; mode=block

Enables XSS filtering. Rather than sanitizing the page, the browser will prevent rendering of the page if an attack is detected.

1; report=<reporting-URI> (Chromium only)

Enables XSS filtering. If a cross-site scripting attack is detected, the browser will sanitize the page and report the violation. This uses the functionality of the CSP `report-uri` directive to send a report.

Vulnerabilities caused by XSS filtering
---------------------------------------

Consider the following excerpt of HTML code for a webpage:

```html
<script>
 var productionMode = true;
</script>
<!-- [...] -->
<script>
 if (!window.productionMode) {
 // Some vulnerable debug code
 }
</script>
```

This code is completely safe if the browser doesn't perform XSS filtering. However, if it does and the search query is `?something=%3Cscript%3Evar%20productionMode%20%3D%20true%3B%3C%2Fscript%3E`, the browser might execute the scripts in the page ignoring `<script>var productionMode = true;</script>` (thinking the server included it in the response because it was in the URI), causing `window.productionMode` to be evaluated to `undefined` and executing the unsafe debug code.

Setting the `X-XSS-Protection` header to either `0` or `1; mode=block` prevents vulnerabilities like the one described above. The former would make the browser run all scripts and the latter would prevent the page from being processed at all (though this approach might be vulnerable to side-channel attacks if the website is embeddable in an `<iframe>`).

Example
-------

Block pages from loading when they detect reflected XSS attacks:

```http
X-XSS-Protection: 1; mode=block
```

PHP

```php
header("X-XSS-Protection: 1; mode=block");
```

Apache (.htaccess)

```apacheconf
<IfModule mod\_headers.c>
  Header set X-XSS-Protection "1; mode=block"
</IfModule>
```

Nginx

```nginx
add\_header "X-XSS-Protection" "1; mode=block";
```

Specifications
--------------

Not part of any specifications or drafts.

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Content-Security-Policy`
* Controlling the XSS Filter – Microsoft
* Understanding XSS Auditor – Virtue Security
* The misunderstood X-XSS-Protection – blog.innerht.ml


Service-Worker-Navigation-Preload - HTTP

Service-Worker-Navigation-Preload
=================================

 The **`Service-Worker-Navigation-Preload`** request header indicates that the request was the result of a `fetch()` operation made during service worker navigation preloading.
 It allows a server to respond with a different resource than for a normal `fetch()`.

If a different response may result from setting this header, the server must set `Vary: Service-Worker-Navigation-Preload` to ensure that the different responses are cached.

For more information see `NavigationPreloadManager.setHeaderValue()` (and `NavigationPreloadManager`).

|  |  |
| --- | --- |
| Header type | Request header |
| Forbidden header name | no |

Syntax
------

```http
Service-Worker-Navigation-Preload: <value>
```

Directives
----------

`<value>`

 An arbitrary value that indicates what data should be sent in the response to the preload request.
 This defaults to `true`.
 It maybe set to any other string value in the service worker, using `NavigationPreloadManager.setHeaderValue()`.

Examples
--------

The header below is sent by default.

```http
Service-Worker-Navigation-Preload: true
```

 The service worker can set a different header value using `NavigationPreloadManager.setHeaderValue()`.
 For example, in order to request that a fragment of the requested resource be returned in JSON format, the value could be set with the string `json_fragment1`.

```http
Service-Worker-Navigation-Preload: json\_fragment1
```

Specifications
--------------

| Specification |
| --- |
| Service Workers # handle-fetch |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


Access-Control-Request-Headers - HTTP

Access-Control-Request-Headers
==============================

The **`Access-Control-Request-Headers`** request header is used by browsers when issuing a preflight request to let the server know which HTTP headers the client might send when the actual request is made (such as with `fetch()` or `XMLHttpRequest.setRequestHeader()`). The complementary server-side header of `Access-Control-Allow-Headers` will answer this browser-side header.

|  |  |
| --- | --- |
| Header type | Request header |
| Forbidden header name | yes |

Syntax
------

```http
Access-Control-Request-Headers: <header-name>, <header-name>, …
```

Directives
----------

<header-name>

A comma-delimited list of HTTP headers that are included in the request.

Examples
--------

```http
Access-Control-Request-Headers: X-PINGOTHER, Content-Type
```

Specifications
--------------

| Specification |
| --- |
| Fetch Standard # http-access-control-request-headers |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Access-Control-Request-Method`


Supports-Loading-Mode - HTTP

Supports-Loading-Mode
=====================

**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

The **`Supports-Loading-Mode`** response header is set by a navigation target to opt-in to using various higher-risk loading modes.

|  |  |
| --- | --- |
| Header type | Response header |
| Forbidden header name | no |
| CORS-safelisted response header | no |

Syntax
------

```http
Supports-Loading-Mode: credentialed-prerender
```

Directives
----------

The `Supports-Loading-Mode` header is a list of one or more tokens, which can include the following values:

`credentialed-prerender`
Experimental

Indicates that a destination origin opts in to loading documents via cross-origin, same-site prerendering.

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Speculation Rules API
* Speculative loading
* Prerender pages in Chrome for instant page navigations on developer.chrome.com (2023)


Via - HTTP

Via
===

 The **`Via`** general header is added by proxies, both forward
 and reverse, and can appear in the request or response headers. It
 is used for tracking message forwards, avoiding request loops, and identifying the
 protocol capabilities of senders along the request/response chain.

|  |  |
| --- | --- |
| Header type | Request header,
 Response header |
| Forbidden header name | yes |

Syntax
------

```http
Via: [ <protocol-name> "/" ] <protocol-version> <host> [ ":" <port> ]
Via: [ <protocol-name> "/" ] <protocol-version> <pseudonym>
```

Directives
----------

<protocol-name>

Optional. The name of the protocol used, such as "HTTP".

<protocol-version>

The version of the protocol used, such as "1.1".

<host> and <port>

Public proxy URL and port.

<pseudonym>

Name/alias of an internal proxy.

Examples
--------

```http
Via: 1.1 vegur
Via: HTTP/1.1 GWA
Via: 1.0 fred, 1.1 p.example.net
```

Specifications
--------------

| Specification |
| --- |
| HTTP Semantics # field.via |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `X-Forwarded-For`
* Heroku's proxy library Vegur


X-Forwarded-Host - HTTP

X-Forwarded-Host
================

 The **`X-Forwarded-Host`** (XFH) header is a de-facto standard
 header for identifying the original host requested by the client in the
 `Host` HTTP request header.

 Host names and ports of reverse proxies (load balancers, CDNs) may differ from the
 origin server handling the request, in that case the `X-Forwarded-Host`
 header is useful to determine which Host was originally used.

|  |  |
| --- | --- |
| Header type | Request header |
| Forbidden header name | no |

Syntax
------

```http
X-Forwarded-Host: <host>
```

Directives
----------

<host>

The domain name of the forwarded server.

Examples
--------

```http
X-Forwarded-Host: id42.example-cdn.com
```

Specifications
--------------

Not part of any current specification.

See also
--------

* `Host`
* `Forwarded`
* `X-Forwarded-For`
* `X-Forwarded-Proto`


TE - HTTP

TE
==

 The **`TE`** request header specifies the transfer encodings
 the user agent is willing to accept. (you could informally call it
 `Accept-Transfer-Encoding`, which would be more intuitive).

**Note:** In
 HTTP/2 and
 HTTP/3, the `TE`
 header field is only accepted if the `trailers` value is set.

 See also the `Transfer-Encoding` response header for more details on
 transfer encodings. Note that `chunked` is always acceptable for HTTP/1.1
 recipients and you don't have to specify `"chunked"` using the
 `TE` header. However, it is useful for setting if the client is accepting
 trailer fields in a chunked transfer coding using the "trailers" value.

|  |  |
| --- | --- |
| Header type | Request header |
| Forbidden header name | yes |

Syntax
------

```http
TE: compress
TE: deflate
TE: gzip
TE: trailers

// Multiple directives, weighted with the quality value syntax:
TE: trailers, deflate;q=0.5
```

Directives
----------

`compress`

 A format using the Lempel-Ziv-Welch (LZW) algorithm is
 accepted as a transfer coding name.

`deflate`

 Using the zlib
 structure is accepted as a transfer coding name.

`gzip`

 A format using the Lempel-Ziv coding
 (LZ77), with a 32-bit CRC is accepted as a transfer coding name.

`trailers`

 Indicates that the client is willing to accept trailer fields in a chunked transfer
 coding.

`q`

 When multiple transfer codings are acceptable, the `q` parameter of the
 quality value syntax can rank
 codings by preference.

Specifications
--------------

| Specification |
| --- |
| HTTP Semantics # field.te |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Transfer-Encoding`
* `Trailer`
* Chunked transfer encoding


X-Frame-Options - HTTP

X-Frame-Options
===============

The **`X-Frame-Options`** HTTP response header can be used to indicate whether a browser should be allowed to render a page in a `<frame>`, `<iframe>`, `<embed>` or `<object>`. Sites can use this to avoid click-jacking attacks, by ensuring that their content is not embedded into other sites.

The added security is provided only if the user accessing the document is using a browser that supports `X-Frame-Options`.

**Warning:** The `Content-Security-Policy` HTTP header has a `frame-ancestors` directive which obsoletes this header for supporting browsers.

|  |  |
| --- | --- |
| Header type | Response header |
| Forbidden header name | no |

Syntax
------

There are two possible directives for `X-Frame-Options`:

```http
X-Frame-Options: DENY
X-Frame-Options: SAMEORIGIN
```

### Directives

If you specify `DENY`, not only will the browser attempt to load the page in a frame fail when loaded from other sites, attempts to do so will fail when loaded from the same site. On the other hand, if you specify `SAMEORIGIN`, you can still use the page in a frame as long as the site including it in a frame is the same as the one serving the page.

`DENY`

The page cannot be displayed in a frame, regardless of the site attempting to do so.

`SAMEORIGIN`

The page can only be displayed if all ancestor frames are same origin to the page itself.

`ALLOW-FROM origin`
Deprecated

This is an obsolete directive. Modern browsers that encounter response headers with this directive will ignore the header completely. The `Content-Security-Policy` HTTP header has a `frame-ancestors` directive which you should use instead.

Examples
--------

**Warning:** Setting `X-Frame-Options` inside the `<meta>` element (e.g., `<meta http-equiv="X-Frame-Options" content="deny">`) has no effect and should not be used! `X-Frame-Options` is only enforced via HTTP headers, as shown in the examples below.

### Configuring Apache

To configure Apache to send the `X-Frame-Options` header for all pages, add this to your site's configuration:

```apacheconf
Header always set X-Frame-Options "SAMEORIGIN"
```

To configure Apache to set `X-Frame-Options` to `DENY`, add this to your site's configuration:

```apacheconf
Header set X-Frame-Options "DENY"
```

### Configuring Nginx

To configure Nginx to send the `X-Frame-Options` header, add this either to your http, server or location configuration:

```nginx
add\_header X-Frame-Options SAMEORIGIN always;
```

You can set the `X-Frame-Options` header to `DENY` using:

```nginx
add\_header X-Frame-Options DENY always;
```

### Configuring IIS

To configure IIS to send the `X-Frame-Options` header, add this to your site's `Web.config` file:

```xml
<system.webServer>
  …
  <httpProtocol>
    <customHeaders>
      <add name="X-Frame-Options" value="SAMEORIGIN" />
    </customHeaders>
  </httpProtocol>
  …
</system.webServer>
```

For more information, see the Microsoft support article on setting this configuration using the IIS Manager user interface.

### Configuring HAProxy

To configure HAProxy to send the `X-Frame-Options` header, add this to your front-end, listen, or backend configuration:
```

rspadd X-Frame-Options:\ SAMEORIGIN
```

Alternatively, in newer versions:
```

http-response set-header X-Frame-Options SAMEORIGIN
```

### Configuring Express

You can use Helmet to configure an Express app to set the **legacy** X-Frame-Options header on old browsers.

**Warning:** It's recommended to use the `Content-Security-Policy` HTTP header with the `frame-ancestors` directive instead.

To use Helmet to set `X-Frame-Options`, add the following to your server configuration to set the `SAMEORIGIN` directive:

```js
const helmet = require("helmet");
const app = express();
app.use(
  helmet({
    xFrameOptions: { action: "sameorigin" },
  }),
);
```

Specifications
--------------

| Specification |
| --- |
| HTML Standard # the-x-frame-options-header |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Content-Security-Policy` directive `frame-ancestors`
* ClickJacking Defenses - IEBlog
* Combating ClickJacking with X-Frame-Options - IEInternals


Sec-Purpose - HTTP

Sec-Purpose
===========

The **`Sec-Purpose`** fetch metadata request header indicates the purpose for which the requested resource will be used, when that purpose is something other than immediate use by the user-agent.

 The only purpose that is currently defined is `prefetch`, which indicates that the resource is being requested in anticipation that it will be needed by a page that is likely to be navigated to in the near future, such as a page linked in search results or a link that a user has hovered over.
 The server can use this knowledge to: adjust the caching expiry for the request, disallow the request, or perhaps to treat it differently when counting page visits.

 The header is sent when a page is loaded that has a `<link>` element with attribute `rel="prefetch"`.
 Note that if this header is set then a `Sec-Fetch-Dest` header in the request must be set to `empty` (any value in the `<link>` attribute `as` is ignored) and the `Accept` header should match the value used for normal navigation requests.

|  |  |
| --- | --- |
| Header type | Fetch Metadata Request Header |
| Forbidden header name | yes (prefix `Sec-`) |
| CORS-safelisted request header | no |

Syntax
------

```http
Sec-Purpose: prefetch
```

Directives
----------

The allowed tokens are:

`prefetch`

The purpose is to prefetch a resource that may be needed in a probable future navigation.

Examples
--------

A prefetch request
------------------

 Consider the case where a browser loads a file with a `<link>` element that has the attribute `rel="prefetch"` and an `href` attribute containing the address of an image file.
 The resulting `fetch()` should result in an HTTP request where `Sec-Purpose: prefetch`, `Sec-Fetch-Dest: empty`, and an `Accept` value that is the same as the browser uses for page navigation.

An example of such a header (on Firefox) is given below:

```http
GET /images/some\_image.png HTTP/1.1
Host: example.com
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/116.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,\*/\*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate, br
Sec-Purpose: prefetch
Connection: keep-alive
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: no-cors
Sec-Fetch-Site: same-origin
Pragma: no-cache
Cache-Control: no-cache
```

**Note:** At time of writing FireFox incorrectly sets the `Accept` header as `Accept: */*` for prefetches.
 The example has been modified to show what the `Accept` value should be.
 This issue can be tracked in Firefox bug 1836334.

Specifications
--------------

| Specification |
| --- |
| Fetch Standard # sec-purpose-header |
| Prefetch # sec-purpose-header |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Prefetch (Glossary)
* `<link>` element with attribute `rel="prefetch"`


If-Range - HTTP

If-Range
========

 The **`If-Range`** HTTP request header makes a range request
 conditional: if the condition is fulfilled, the range request is issued, and the
 server sends back a `206` `Partial Content` answer with the
 appropriate body. If the condition is not fulfilled, the full resource is sent back
 with a `200` `OK` status.

 This header can be used either with the `Last-Modified` validator or
 with `ETag`, but not with both.

 The most common use case is to resume a download, to guarantee that the stored resource
 has not been modified since the last fragment has been received.

|  |  |
| --- | --- |
| Header type | Request header |
| Forbidden header name | no |

Syntax
------

```http
If-Range: <day-name>, <day> <month> <year> <hour>:<minute>:<second> GMT
If-Range: <etag>
```

Directives
----------

<etag>

 An entity tag uniquely representing the requested resource. It is a string of ASCII
 characters placed between double quotes (Like `"675af34563dc-tr34"`). A weak entity tag (one prefixed by `W/`) must not be used in this header.

<day-name>

One of "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", or "Sun" (case-sensitive).

<day>

2 digit day number, e.g. "04" or "23".

<month>

 One of "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov",
 "Dec" (case-sensitive).

<year>

4 digit year number, e.g. "1990" or "2016".

<hour>

2 digit hour number, e.g. "09" or "23".

<minute>

2 digit minute number, e.g. "04" or "59".

<second>

2 digit second number, e.g. "04" or "59".

`GMT`

Greenwich Mean Time. HTTP dates are always expressed in GMT, never in local time.

Examples
--------

```http
If-Range: Wed, 21 Oct 2015 07:28:00 GMT
```

Specifications
--------------

| Specification |
| --- |
| HTTP Semantics # field.if-range |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `ETag`
* `Last-Modified`
* `If-Modified-Since`
* `If-Unmodified-Since`
* `If-Match`
* `If-None-Match`
* `206 Partial Content`
* HTTP Conditional Requests


Sec-Fetch-Dest - HTTP

Sec-Fetch-Dest
==============

The **`Sec-Fetch-Dest`** fetch metadata request header indicates the request's *destination*. That is the initiator of the original fetch request, which is where (and how) the fetched data will be used.

This allows servers determine whether to service a request based on whether it is appropriate for how it is *expected* to be used. For example, a request with an `audio` destination should request audio data, not some other type of resource (for example, a document that includes sensitive user information).

|  |  |
| --- | --- |
| Header type | Fetch Metadata Request Header |
| Forbidden header name | yes (prefix `Sec-`) |
| CORS-safelisted request header | no |

Syntax
------

```http
Sec-Fetch-Dest: audio
Sec-Fetch-Dest: audioworklet
Sec-Fetch-Dest: document
Sec-Fetch-Dest: embed
Sec-Fetch-Dest: empty
Sec-Fetch-Dest: font
Sec-Fetch-Dest: frame
Sec-Fetch-Dest: iframe
Sec-Fetch-Dest: image
Sec-Fetch-Dest: manifest
Sec-Fetch-Dest: object
Sec-Fetch-Dest: paintworklet
Sec-Fetch-Dest: report
Sec-Fetch-Dest: script
Sec-Fetch-Dest: serviceworker
Sec-Fetch-Dest: sharedworker
Sec-Fetch-Dest: style
Sec-Fetch-Dest: track
Sec-Fetch-Dest: video
Sec-Fetch-Dest: worker
Sec-Fetch-Dest: xslt
```

Servers should ignore this header if it contains any other value.

Directives
----------

**Note:** These directives correspond to the values returned by `Request.destination`.

`audio`

The destination is audio data. This might originate from an HTML `<audio>` tag.

`audioworklet`

The destination is data being fetched for use by an audio worklet. This might originate from a call to `audioWorklet.addModule()`.

`document`

The destination is a document (HTML or XML), and the request is the result of a user-initiated top-level navigation (e.g. resulting from a user clicking a link).

`embed`

The destination is embedded content. This might originate from an HTML `<embed>` tag.

`empty`

The destination is the empty string. This is used for destinations that do not have their own value. For example: `fetch()`, `navigator.sendBeacon()`, `EventSource`, `XMLHttpRequest`, `WebSocket`, etc.

`font`

The destination is a font. This might originate from CSS `@font-face`.

`frame`

The destination is a frame. This might originate from an HTML `<frame>` tag.

`iframe`

The destination is an iframe. This might originate from an HTML `<iframe>` tag.

`image`

The destination is an image. This might originate from an HTML `<img>`, SVG `<image>`, CSS `background-image`, CSS `cursor`, CSS `list-style-image`, etc.

`manifest`

The destination is a manifest. This might originate from an HTML <link rel=manifest>.

`object`

The destination is an object. This might originate from an HTML `<object>` tag.

`paintworklet`

The destination is a paint worklet. This might originate from a call to `CSS.PaintWorklet.addModule()`.

`report`

The destination is a report (for example, a content security policy report).

`script`

The destination is a script. This might originate from an HTML `<script>` tag or a call to `WorkerGlobalScope.importScripts()`.

`serviceworker`

The destination is a service worker. This might originate from a call to `navigator.serviceWorker.register()`.

`sharedworker`

The destination is a shared worker. This might originate from a `SharedWorker`.

`style`

The destination is a style. This might originate from an HTML <link rel=stylesheet> or a CSS `@import`.

`track`

The destination is an HTML text track. This might originate from an HTML `<track>` tag.

`video`

The destination is video data. This might originate from an HTML `<video>` tag.

`worker`

The destination is a `Worker`.

`xslt`

The destination is an XSLT transform.

Examples
--------

A cross-site request generated by an `<img>` element would result in a request with the following HTTP request headers (note that the destination is `image`):

```http
Sec-Fetch-Dest: image
Sec-Fetch-Mode: no-cors
Sec-Fetch-Site: cross-site
```

Specifications
--------------

| Specification |
| --- |
| Fetch Metadata Request Headers # sec-fetch-dest-header |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Related headers
    + `Sec-Fetch-Mode`
    + `Sec-Fetch-Site`
    + `Sec-Fetch-User`
* Protect your resources from web attacks with Fetch Metadata (web.dev)
* Fetch Metadata Request Headers playground (secmetadata.appspot.com)