An overview of HTTP - HTTP

An overview of HTTP
===================

**HTTP** is a protocol for fetching resources such as HTML documents.
 It is the foundation of any data exchange on the Web and it is a client-server protocol, which means requests are initiated by the recipient, usually the Web browser.
 A complete document is reconstructed from the different sub-documents fetched, for instance, text, layout description, images, videos, scripts, and more.

![A Web document is the composition of different resources](/en-US/docs/Web/HTTP/Overview/fetching_a_page.png)

 Clients and servers communicate by exchanging individual messages (as opposed to a stream of data).
 The messages sent by the client, usually a Web browser, are called *requests* and the messages sent by the server as an answer are called *responses*.

![HTTP as an application layer protocol, on top of TCP (transport layer) and IP (network layer) and below the presentation layer.](/en-US/docs/Web/HTTP/Overview/http-layers.png)Designed in the early 1990s, HTTP is an extensible protocol which has evolved over time.
 It is an application layer protocol that is sent over TCP, or over a TLS-encrypted TCP connection, though any reliable transport protocol could theoretically be used.
 Due to its extensibility, it is used to not only fetch hypertext documents, but also images and videos or to post content to servers, like with HTML form results.
 HTTP can also be used to fetch parts of documents to update Web pages on demand.

Components of HTTP-based systems
--------------------------------

 HTTP is a client-server protocol: requests are sent by one entity, the user-agent (or a proxy on behalf of it).
 Most of the time the user-agent is a Web browser, but it can be anything, for example, a robot that crawls the Web to populate and maintain a search engine index.

 Each individual request is sent to a server, which handles it and provides an answer called the *response*.
 Between the client and the server there are numerous entities, collectively called proxies, which perform different operations and act as gateways or caches, for example.

![Client server chain](/en-US/docs/Web/HTTP/Overview/client-server-chain.png)

 In reality, there are more computers between a browser and the server handling the request: there are routers, modems, and more.
 Thanks to the layered design of the Web, these are hidden in the network and transport layers.
 HTTP is on top, at the application layer.
 Although important for diagnosing network problems, the underlying layers are mostly irrelevant to the description of HTTP.

### Client: the user-agent

 The *user-agent* is any tool that acts on behalf of the user.
 This role is primarily performed by the Web browser, but it may also be performed by programs used by engineers and Web developers to debug their applications.

 The browser is **always** the entity initiating the request.
 It is never the server (though some mechanisms have been added over the years to simulate server-initiated messages).

 To display a Web page, the browser sends an original request to fetch the HTML document that represents the page.
 It then parses this file, making additional requests corresponding to execution scripts, layout information (CSS) to display, and sub-resources contained within the page (usually images and videos).
 The Web browser then combines these resources to present the complete document, the Web page.
 Scripts executed by the browser can fetch more resources in later phases and the browser updates the Web page accordingly.

 A Web page is a hypertext document.
 This means some parts of the displayed content are links, which can be activated (usually by a click of the mouse) to fetch a new Web page, allowing the user to direct their user-agent and navigate through the Web.
 The browser translates these directions into HTTP requests, and further interprets the HTTP responses to present the user with a clear response.

### The Web server

 On the opposite side of the communication channel is the server, which *serves* the document as requested by the client.
 A server appears as only a single machine virtually; but it may actually be a collection of servers sharing the load (load balancing), or other software (such as caches, a database server, or e-commerce servers), totally or partially generating the document on demand.

 A server is not necessarily a single machine, but several server software instances can be hosted on the same machine.
 With HTTP/1.1 and the `Host` header, they may even share the same IP address.

### Proxies

 Between the Web browser and the server, numerous computers and machines relay the HTTP messages.
 Due to the layered structure of the Web stack, most of these operate at the transport, network or physical levels, becoming transparent at the HTTP layer and potentially having a significant impact on performance.
 Those operating at the application layers are generally called **proxies**.
 These can be transparent, forwarding on the requests they receive without altering them in any way, or non-transparent, in which case they will change the request in some way before passing it along to the server.
 Proxies may perform numerous functions:

* caching (the cache can be public or private, like the browser cache)
* filtering (like an antivirus scan or parental controls)
* load balancing (to allow multiple servers to serve different requests)
* authentication (to control access to different resources)
* logging (allowing the storage of historical information)
Basic aspects of HTTP
---------------------

### HTTP is simple

 HTTP is generally designed to be simple and human-readable, even with the added complexity introduced in HTTP/2 by encapsulating HTTP messages into frames.
 HTTP messages can be read and understood by humans, providing easier testing for developers, and reduced complexity for newcomers.

### HTTP is extensible

 Introduced in HTTP/1.0, HTTP headers make this protocol easy to extend and experiment with.
 New functionality can even be introduced by a simple agreement between a client and a server about a new header's semantics.

### HTTP is stateless, but not sessionless

 HTTP is stateless: there is no link between two requests being successively carried out on the same connection.
 This immediately has the prospect of being problematic for users attempting to interact with certain pages coherently, for example, using e-commerce shopping baskets.
 But while the core of HTTP itself is stateless, HTTP cookies allow the use of stateful sessions.
 Using header extensibility, HTTP Cookies are added to the workflow, allowing session creation on each HTTP request to share the same context, or the same state.

### HTTP and connections

 A connection is controlled at the transport layer, and therefore fundamentally out of scope for HTTP.
 HTTP doesn't require the underlying transport protocol to be connection-based; it only requires it to be *reliable*, or not lose messages (at minimum, presenting an error in such cases).
 Among the two most common transport protocols on the Internet, TCP is reliable and UDP isn't.
 HTTP therefore relies on the TCP standard, which is connection-based.

 Before a client and server can exchange an HTTP request/response pair, they must establish a TCP connection, a process which requires several round-trips.
 The default behavior of HTTP/1.0 is to open a separate TCP connection for each HTTP request/response pair.
 This is less efficient than sharing a single TCP connection when multiple requests are sent in close succession.

 In order to mitigate this flaw, HTTP/1.1 introduced *pipelining* (which proved difficult to implement) and *persistent connections*: the underlying TCP connection can be partially controlled using the `Connection` header.
 HTTP/2 went a step further by multiplexing messages over a single connection, helping keep the connection warm and more efficient.

 Experiments are in progress to design a better transport protocol more suited to HTTP.
 For example, Google is experimenting with QUIC which builds on UDP to provide a more reliable and efficient transport protocol.

What can be controlled by HTTP
------------------------------

 This extensible nature of HTTP has, over time, allowed for more control and functionality of the Web.
 Cache and authentication methods were functions handled early in HTTP history.
 The ability to relax the *origin constraint*, by contrast, was only added in the 2010s.

Here is a list of common features controllable with HTTP:

* *Caching*:
 How documents are cached can be controlled by HTTP.
 The server can instruct proxies and clients about what to cache and for how long.
 The client can instruct intermediate cache proxies to ignore the stored document.
* *Relaxing the origin constraint*:
 To prevent snooping and other privacy invasions, Web browsers enforce strict separation between websites.
 Only pages from the **same origin** can access all the information of a Web page.
 Though such a constraint is a burden to the server, HTTP headers can relax this strict separation on the server side, allowing a document to become a patchwork of information sourced from different domains; there could even be security-related reasons to do so.
* *Authentication*:
 Some pages may be protected so that only specific users can access them.
 Basic authentication may be provided by HTTP, either using the `WWW-Authenticate` and similar headers, or by setting a specific session using HTTP cookies.
* *Proxy and tunneling*:
 Servers or clients are often located on intranets and hide their true IP address from other computers.
 HTTP requests then go through proxies to cross this network barrier.
 Not all proxies are HTTP proxies.
 The SOCKS protocol, for example, operates at a lower level.
 Other protocols, like ftp, can be handled by these proxies.
* *Sessions*:
 Using HTTP cookies allows you to link requests with the state of the server.
 This creates sessions, despite basic HTTP being a state-less protocol.
 This is useful not only for e-commerce shopping baskets, but also for any site allowing user configuration of the output.
HTTP flow
---------

When a client wants to communicate with a server, either the final server or an intermediate proxy, it performs the following steps:

1. Open a TCP connection: The TCP connection is used to send a request, or several, and receive an answer.
 The client may open a new connection, reuse an existing connection, or open several TCP connections to the servers.
2. Send an HTTP message: HTTP messages (before HTTP/2) are human-readable.
 With HTTP/2, these simple messages are encapsulated in frames, making them impossible to read directly, but the principle remains the same.
 For example:

```http
GET / HTTP/1.1
Host: developer.mozilla.org
Accept-Language: fr
```

3. Read the response sent by the server, such as:

```http
HTTP/1.1 200 OK
Date: Sat, 09 Oct 2010 14:28:02 GMT
Server: Apache
Last-Modified: Tue, 01 Dec 2009 20:18:22 GMT
ETag: "51142bc1-7449-479b075b2891b"
Accept-Ranges: bytes
Content-Length: 29769
Content-Type: text/html

<!DOCTYPE html>… (here come the 29769 bytes of the requested web page)
```

4. Close or reuse the connection for further requests.

 If HTTP pipelining is activated, several requests can be sent without waiting for the first response to be fully received.
 HTTP pipelining has proven difficult to implement in existing networks, where old pieces of software coexist with modern versions.
 HTTP pipelining has been superseded in HTTP/2 with more robust multiplexing requests within a frame.

HTTP Messages
-------------

 HTTP messages, as defined in HTTP/1.1 and earlier, are human-readable.
 In HTTP/2, these messages are embedded into a binary structure, a *frame*, allowing optimizations like compression of headers and multiplexing.
 Even if only part of the original HTTP message is sent in this version of HTTP, the semantics of each message is unchanged and the client reconstitutes (virtually) the original HTTP/1.1 request.
 It is therefore useful to comprehend HTTP/2 messages in the HTTP/1.1 format.

There are two types of HTTP messages, requests and responses, each with its own format.

### Requests

An example HTTP request:

![A basic HTTP request](/en-US/docs/Web/HTTP/Overview/http_request.png)

Requests consist of the following elements:

* An HTTP method, usually a verb like `GET`, `POST`, or a noun like `OPTIONS` or `HEAD` that defines the operation the client wants to perform.
 Typically, a client wants to fetch a resource (using `GET`) or post the value of an HTML form (using `POST`), though more operations may be needed in other cases.
* The path of the resource to fetch; the URL of the resource stripped from elements that are obvious from the context, for example without the protocol (`http://`), the domain (here, `developer.mozilla.org`), or the TCP port (here, `80`).
* The version of the HTTP protocol.
* Optional headers that convey additional information for the servers.
* A body, for some methods like `POST`, similar to those in responses, which contain the resource sent.
### Responses

An example response:

![HTTP Response image](/en-US/docs/Web/HTTP/Overview/http_response.png)

Responses consist of the following elements:

* The version of the HTTP protocol they follow.
* A status code, indicating if the request was successful or not, and why.
* A status message, a non-authoritative short description of the status code.
* HTTP headers, like those for requests.
* Optionally, a body containing the fetched resource.
APIs based on HTTP
------------------

The most commonly used API based on HTTP is the Fetch API, which can be used to make HTTP requests from JavaScript. The Fetch API replaces the `XMLHttpRequest` API.

 Another API, server-sent events, is a one-way service that allows a server to send events to the client, using HTTP as a transport mechanism.
 Using the `EventSource` interface, the client opens a connection and establishes event handlers.
 The client browser automatically converts the messages that arrive on the HTTP stream into appropriate `Event` objects. Then it delivers them to the event handlers that have been registered for the events' `type` if known, or to the `onmessage` event handler if no type-specific event handler was established.

Conclusion
----------

 HTTP is an extensible protocol that is easy to use.
 The client-server structure, combined with the ability to add headers, allows HTTP to advance along with the extended capabilities of the Web.

 Though HTTP/2 adds some complexity by embedding HTTP messages in frames to improve performance, the basic structure of messages has stayed the same since HTTP/1.0.
 Session flow remains simple, allowing it to be investigated and debugged with a simple HTTP message monitor.


Redirections in HTTP - HTTP

Redirections in HTTP
====================

**URL redirection**, also known as *URL forwarding*, is a technique to give more than one URL address to a page, a form, a whole website, or a web application. HTTP has a special kind of response, called a ***HTTP redirect***, for this operation.

Redirects accomplish numerous goals:

* Temporary redirects during site maintenance or downtime
* Permanent redirects to preserve existing links/bookmarks after changing the site's URLs, progress pages when uploading a file, etc.
Principle
---------

In HTTP, redirection is triggered by a server sending a special *redirect* response to a request. Redirect responses have status codes that start with `3`, and a `Location` header holding the URL to redirect to.

When browsers receive a redirect, they immediately load the new URL provided in the `Location` header. Besides the small performance hit of an additional round-trip, users rarely notice the redirection.

![Initial request goes from client to server. Server responds with a 301:moved permanently, with the URL for the redirect. Client makes an a GET request for the new URL which is returned by the server, with a 200 OK response.](/en-US/docs/Web/HTTP/Redirections/httpredirect.png)

There are several types of redirects, sorted into three categories:

1. Permanent redirections
2. Temporary redirections
3. Special redirections
### Permanent redirections

These redirections are meant to last forever. They imply that the original URL should no longer be used, and replaced with the new one. Search engine robots, RSS readers, and other crawlers will update the original URL for the resource.

| Code | Text | Method handling | Typical use case |
| --- | --- | --- | --- |
| `301` | `Moved Permanently` | `GET` methods unchanged. Others may or may not be changed to `GET`. [1] | Reorganization of a website. |
| `308` | `Permanent Redirect` | Method and body not changed. | Reorganization of a website, with non-GET links/operations. |

[1] The specification did not intend to allow method changes, but there are existing user agents that do change their method. `308` was created to remove the ambiguity of the behavior when using non-`GET` methods.

### Temporary redirections

Sometimes the requested resource can't be accessed from its canonical location, but it can be accessed from another place. In this case, a temporary redirect can be used.

Search engine robots and other crawlers don't memorize the new, temporary URL. Temporary redirections are also used when creating, updating, or deleting resources, to show temporary progress pages.

| Code | Text | Method handling | Typical use case |
| --- | --- | --- | --- |
| `302` | `Found` | `GET` methods unchanged. Others may or may not be changed to `GET`. [2] | The Web page is temporarily unavailable for unforeseen reasons. |
| `303` | `See Other` | `GET` methods unchanged. Others *changed* to `GET` (body lost). | Used to redirect after a `PUT` or a `POST`, so that refreshing the result page doesn't re-trigger the operation. |
| `307` | `Temporary Redirect` | Method and body not changed | The Web page is temporarily unavailable for unforeseen reasons. Better than `302` when non-`GET` operations are available on the site. |

[2] The specification did not intend to allow method changes, but there are existing user agents that do change their method. `307` was created to remove the ambiguity of the behavior when using non-`GET` methods.

### Special redirections

`304` (Not Modified) redirects a page to the locally cached copy (that was stale), and `300` (Multiple Choices) is a manual redirection: the body, presented by the browser as a Web page, lists the possible redirections and the user clicks on one to select it.

| Code | Text | Typical use case |
| --- | --- | --- |
| `300` | `Multiple Choices` | Not many: the choices are listed in an HTML page in the body. Machine-readable choices are encouraged to be sent as `Link` headers with `rel=alternate`. |
| `304` | `Not Modified` | Sent for revalidated conditional requests. Indicates that the cached response is still fresh and can be used. |

Alternative way of specifying redirections
------------------------------------------

HTTP redirects aren't the only way to define redirections. There are two others:

1. HTML redirections with the `<meta>` element
2. JavaScript redirections via the DOM
### HTML redirections

HTTP redirects are the best way to create redirections, but sometimes you don't have control over the server. In that case, try a `<meta>` element with its `http-equiv` attribute set to `Refresh` in the `<head>` of the page. When displaying the page, the browser will go to the indicated URL.

```html
<head>
  <meta http-equiv="Refresh" content="0; URL=https://example.com/" />
</head>
```

The `content` attribute should start with a number indicating how many seconds the browser should wait before redirecting to the given URL. Always set it to `0` for accessibility compliance.

Obviously, this method only works with HTML, and cannot be used for images or other types of content.

### JavaScript redirections

Redirections in JavaScript are performed by setting a URL string to the `window.location` property, loading the new page:

```js
window.location = "https://example.com/";
```

Like HTML redirections, this can't work on all resources, and obviously, this will only work on clients that execute JavaScript. On the other hand, there are more possibilities: for example, you can trigger the redirect only if some conditions are met.

### Order of precedence

With three ways to trigger redirections, several ways can be used at the same time. But which is applied first?

1. HTTP redirects always execute first — they exist when there is not even a transmitted page.
2. HTML redirects (`<meta>`) execute if there weren't any HTTP redirects.
3. JavaScript redirects execute last, and only if JavaScript is enabled.

When possible, use HTTP redirects and don't add `<meta>` element redirects. If someone changes the HTTP redirects but forgets to change the HTML redirects, the redirects will no longer be identical, which could cause an infinite loop or other nightmares.

Use cases
---------

There are numerous use cases for redirects, but as performance is impacted with every redirect, their use should be kept to a minimum.

### Domain aliasing

Ideally, there is one location, and therefore one URL, for each resource. But there are reasons for alternative names for a resource:

Expanding the reach of your site

A common case is when a site resides at `www.example.com`, but accessing it from `example.com` should also work. Redirections for `example.com` to `www.example.com` are thus set up. You might also redirect from common synonyms or frequent typos of your domains.

Moving to a new domain

For example, your company was renamed, but you want existing links or bookmarks to still find you under the new name.

Forcing HTTPS

Requests to the `http://` version of your site will redirect to the `https://` version of your site.

### Keeping links alive

When you restructure websites, URLs change. Even if you update your site's links to match the new URLs, you have no control over the URLs used by external resources.

You don't want to break these links, as they bring valuable users and help your SEO, so you set up redirects from the old URLs to the new ones.

**Note:** This technique does work for internal links, but try to avoid having internal redirects. A redirect has a significant performance cost (as an extra HTTP request occurs). If you can avoid it by correcting internal links, you should fix those links instead.

### Temporary responses to unsafe requests

Unsafe requests modify the state of the server and the user shouldn't resend them unintentionally.

Typically, you don't want your users to resend `PUT`, `POST` or `DELETE` requests. If you serve the response as the result of this request, a simple press of the reload button will resend the request (possibly after a confirmation message).

In this case, the server can send back a `303` (See Other) response for a URL that will contain the right information. If the reload button is pressed, only that page is redisplayed, without replaying the unsafe requests.

### Temporary responses to long requests

Some requests may need more time on the server, like `DELETE` requests that are scheduled for later processing. In this case, the response is a `303` (See Other) redirect that links to a page indicating that the action has been scheduled, and eventually informs about its progress, or allows to cancel it.

Configuring redirects in common servers
---------------------------------------

### Apache

Redirects can be set either in the server config file or in the `.htaccess` of each directory.

The `mod_alias` module has `Redirect` and `RedirectMatch` directives that set up `302` redirects by default:

```xml
<VirtualHost \*:443>
  ServerName example.com
  Redirect / https://www.example.com
</VirtualHost>
```

The URL `https://example.com/` will be redirected to `https://www.example.com/`, as will any files or directories under it (`https://example.com/some-page` will be redirected to `https://www.example.com/some-page`)

`RedirectMatch` does the same, but takes a regular expression to define a collection of affected URLs:
```

RedirectMatch ^/images/(.*)$ https://images.example.com/$1
```

All documents in the `images/` directory will redirect to a different domain.

If you don't want a temporary redirect, an extra parameter (either the HTTP status code to use or the `permanent` keyword) can be used to set up a different redirect:
```

Redirect permanent / https://www.example.com
# …acts the same as:
Redirect 301 / https://www.example.com
```

The `mod_rewrite` module can also create redirects. It is more flexible, but a bit more complex.

### Nginx

In Nginx, you create a specific server block for the content you want to redirect:
```

server {
  listen 80;
  server_name example.com;
  return 301 $scheme://www.example.com$request_uri;
}
```

To apply a redirect to a directory or only certain pages, use the `rewrite` directive:
```

rewrite ^/images/(.*)$ https://images.example.com/$1 redirect;
rewrite ^/images/(.*)$ https://images.example.com/$1 permanent;
```

### IIS

In IIS, you use the `<httpRedirect>` element to configure redirections.

Redirection loops
-----------------

Redirection loops happen when additional redirections follow the one that has already been followed. In other words, there is a loop that will never be finished and no page will ever be found.

Most of the time this is a server problem, and if the server can detect it, it will send back a `500` `Internal Server Error`. If you encounter such an error soon after modifying a server configuration, this is likely a redirection loop.

Sometimes, the server won't detect it: a redirection loop can spread over several servers which each don't have the full picture. In this case, browsers will detect it and display an error message. Firefox displays:

>
> Firefox has detected that the server is redirecting the request for this address in a way that will never terminate.
>
>
>

…while Chrome displays:

>
> This Webpage has a redirect loop
>
>
>

In both cases, the user can't do much (unless corruption is happening on their side, like a mismatch of cache or cookies).

It is important to avoid redirection loops, as they completely break the user experience.


HTTP request methods - HTTP

HTTP request methods
====================

HTTP defines a set of **request methods** to indicate the desired action to be performed for a given resource. Although they can also be nouns, these request methods are sometimes referred to as *HTTP verbs*. Each of them implements a different semantic, but some common features are shared by a group of them: e.g. a request method can be safe, idempotent, or cacheable.

`GET`

The `GET` method requests a representation of the specified resource. Requests using `GET` should only retrieve data.

`HEAD`

The `HEAD` method asks for a response identical to a `GET` request, but without the response body.

`POST`

The `POST` method submits an entity to the specified resource, often causing a change in state or side effects on the server.

`PUT`

The `PUT` method replaces all current representations of the target resource with the request payload.

`DELETE`

The `DELETE` method deletes the specified resource.

`CONNECT`

The `CONNECT` method establishes a tunnel to the server identified by the target resource.

`OPTIONS`

The `OPTIONS` method describes the communication options for the target resource.

`TRACE`

The `TRACE` method performs a message loop-back test along the path to the target resource.

`PATCH`

The `PATCH` method applies partial modifications to a resource.

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

| Specification |
| --- |
| HTTP Semantics # CONNECT |
| HTTP Semantics # DELETE |
| HTTP Semantics # GET |
| HTTP Semantics # HEAD |
| HTTP Semantics # OPTIONS |
| HTTP Semantics # POST |
| HTTP Semantics # PUT |
| HTTP Semantics # TRACE |

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

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

See also
--------

* HTTP headers


HTTP range requests - HTTP

HTTP range requests
===================

An HTTP `Range` request asks the server to send only a portion of an HTTP message back to a client. Range requests are useful for clients like media players that support random access, data tools that know they need only part of a large file, and download managers that let the user pause and resume the download.

Checking if a server supports partial requests
----------------------------------------------

If an HTTP response includes the `Accept-Ranges` header and its value is anything other than "`none`", then the server supports range requests. You can perform a manual check by issuing a `HEAD` request with a tool like cURL.

```bash
curl -I http://i.imgur.com/z4d4kWk.jpg
```

```http
HTTP/1.1 200 OK
…
Accept-Ranges: bytes
Content-Length: 146515
```

In this response, `Accept-Ranges: bytes` indicates that bytes can be used as units to define a range. Here the `Content-Length` header is also useful as it indicates the full size of the image to retrieve.

If sites omit the `Accept-Ranges` header, they likely don't support partial requests. Some sites include the header but give it the explicit value "`none`" to indicate they lack support:

```bash
curl -I https://www.youtube.com/watch?v=EwTZ2xpQwpA
```

```http
HTTP/1.1 200 OK
…
Accept-Ranges: none
```

A download manager might disable its pause button in that case.

Requesting a specific range from a server
-----------------------------------------

If the server supports range requests, then by including the `Range` header in your HTTP request, you can specify which part or parts of the document you want the server to return.

### Single part ranges

We can request a single range from a resource. Again, we can test a request by using cURL. The "`-H`" option will append a header line to the request, which in this case is the `Range` header requesting the first 1024 bytes.

```bash
curl http://i.imgur.com/z4d4kWk.jpg -i -H "Range: bytes=0-1023"
```

The issued request looks like this:

```http
GET /z4d4kWk.jpg HTTP/1.1
Host: i.imgur.com
Range: bytes=0-1023
```

The server responses with the `206` `Partial Content` status:

```http
HTTP/1.1 206 Partial Content
Content-Range: bytes 0-1023/146515
Content-Length: 1024
…
(binary content)
```

The `Content-Length` header now indicates the size of the requested range (and not the full size of the image). The `Content-Range` response header indicates where in the full resource this partial message belongs.

### Multipart ranges

The `Range` header also allows you to get multiple ranges at once in a multipart document. The ranges are separated by a comma.

```bash
curl http://www.example.com -i -H "Range: bytes=0-50, 100-150"
```

The server responses with the `206` `Partial Content` status and a `Content-Type``: multipart/byteranges; boundary=3d6b6a416f9b5` header, indicating that a multipart byterange follows. Each part contains its own `Content-Type` and `Content-Range` fields and the required boundary parameter specifies the boundary string used to separate each body-part.

```http
HTTP/1.1 206 Partial Content
Content-Type: multipart/byteranges; boundary=3d6b6a416f9b5
Content-Length: 282

--3d6b6a416f9b5
Content-Type: text/html
Content-Range: bytes 0-50/1270

<!DOCTYPE html>
<html lang="en-US">
<head>
 <title>Example Do
--3d6b6a416f9b5
Content-Type: text/html
Content-Range: bytes 100-150/1270

eta http-equiv="Content-type" content="text/html; c
--3d6b6a416f9b5--
```

### Conditional range requests

When resuming to request more parts of a resource, you need to guarantee that the stored resource has not been modified since the last fragment has been received.

The `If-Range` HTTP request header makes a range request conditional: if the condition is fulfilled, the range request will be 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 a `Last-Modified` validator, or with an `ETag`, but not with both.

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

Partial request responses
-------------------------

There are three relevant statuses, when working with range requests:

* A successful range request elicits a `206` `Partial Content` status from the server.
* A range request that is out of bounds will result in a `416` `Requested Range Not Satisfiable` status, meaning that none of the range values overlap the extent of the resource. For example, the first-byte-pos of every range might be greater than the resource length.
* If range requests are not supported, an `200` `OK` status is sent back and the entire response body is transmitted.
Comparison to chunked `Transfer-Encoding`
-----------------------------------------

The `Transfer-Encoding` header allows chunked encoding, which is useful when larger amounts of data are sent to the client and the total size of the response is not known until the request has been fully processed. The server sends data to the client straight away without buffering the response or determining the exact length, which leads to improved latency. Range requests and chunking are compatible and can be used with or without each other.

See also
--------

* Related status codes `200`, `206`, `416`.
* Related headers: `Accept-Ranges`, `Range`, `Content-Range`, `If-Range`, `Transfer-Encoding`.


Connection management in HTTP/1.x - HTTP

Connection management in HTTP/1.x
=================================

Connection management is a key topic in HTTP: opening and maintaining connections largely impacts the performance of websites and Web applications. In HTTP/1.x, there are several models: *short-lived connections*, *persistent connections*, and *HTTP pipelining.*

HTTP mostly relies on TCP for its transport protocol, providing a connection between the client and the server. In its infancy, HTTP used a single model to handle such connections. These connections were short-lived: a new one created each time a request needed sending, and closed once the answer had been received.

This simple model held an innate limitation on performance: opening each TCP connection is a resource-consuming operation. Several messages must be exchanged between the client and the server. Network latency and bandwidth affect performance when a request needs sending. Modern Web pages require many requests (a dozen or more) to serve the amount of information needed, proving this earlier model inefficient.

Two newer models were created in HTTP/1.1. The persistent-connection model keeps connections opened between successive requests, reducing the time needed to open new connections. The HTTP pipelining model goes one step further, by sending several successive requests without even waiting for an answer, reducing much of the latency in the network.

![Compares the performance of the three HTTP/1.x connection models: short-lived connections, persistent connections, and HTTP pipelining.](/en-US/docs/Web/HTTP/Connection_management_in_HTTP_1.x/http1_x_connections.png)

**Note:** HTTP/2 adds additional models for connection management.

It's important to note that connection management in HTTP applies to the connection between two consecutive nodes, which is hop-by-hop and not end-to-end. The model used in connections between a client and its first proxy may differ from the model between a proxy and the destination server (or any intermediate proxies). The HTTP headers involved in defining the connection model, like `Connection` and `Keep-Alive`, are hop-by-hop headers with their values able to be changed by intermediary nodes.

A related topic is the concept of HTTP connection upgrades, wherein an HTTP/1.1 connection is upgraded to a different protocol, such as TLS/1.0, WebSocket, or even HTTP/2 in cleartext. This protocol upgrade mechanism is documented in more detail elsewhere.

Short-lived connections
-----------------------

The original model of HTTP, and the default one in HTTP/1.0, is *short-lived connections*. Each HTTP request is completed on its own connection; this means a TCP handshake happens before each HTTP request, and these are serialized.

The TCP handshake itself is time-consuming, but a TCP connection adapts to its load, becoming more efficient with more sustained (or warm) connections. Short-lived connections do not make use of this efficiency feature of TCP, and performance degrades from optimum by persisting to transmit over a new, cold connection.

This model is the default model used in HTTP/1.0 (if there is no `Connection` header, or if its value is set to `close`). In HTTP/1.1, this model is only used when the `Connection` header is sent with a value of `close`.

**Note:** Unless dealing with a very old system, which doesn't support a persistent connection, there is no compelling reason to use this model.

Persistent connections
----------------------

Short-lived connections have two major hitches: the time taken to establish a new connection is significant, and performance of the underlying TCP connection gets better only when this connection has been in use for some time (warm connection). To ease these problems, the concept of a *persistent connection* has been designed, even prior to HTTP/1.1. Alternatively this may be called a *keep-alive connection*.

A persistent connection is one which remains open for a period of time, and can be reused for several requests, saving the need for a new TCP handshake, and utilizing TCP's performance enhancing capabilities. This connection will not stay open forever: idle connections are closed after some time (a server may use the `Keep-Alive` header to specify a minimum time the connection should be kept open).

Persistent connections also have drawbacks; even when idling they consume server resources, and under heavy load, DoS attacks can be conducted. In such cases, using non-persistent connections, which are closed as soon as they are idle, can provide better performance.

HTTP/1.0 connections are not persistent by default. Setting `Connection` to anything other than `close`, usually `retry-after`, will make them persistent.

In HTTP/1.1, persistence is the default, and the header is no longer needed (but it is often added as a defensive measure against cases requiring a fallback to HTTP/1.0).

HTTP pipelining
---------------

**Note:** HTTP pipelining is not activated by default in modern browsers:

* Buggy proxies are still common and these lead to strange and erratic behaviors that Web developers cannot foresee and diagnose easily.
* Pipelining is complex to implement correctly: the size of the resource being transferred, the effective RTT that will be used, as well as the effective bandwidth, have a direct incidence on the improvement provided by the pipeline. Without knowing these, important messages may be delayed behind unimportant ones. The notion of important even evolves during page layout! HTTP pipelining therefore brings a marginal improvement in most cases only.
* Pipelining is subject to the HOL problem.

For these reasons, pipelining has been superseded by a better algorithm, *multiplexing*, that is used by HTTP/2.

By default, HTTP requests are issued sequentially. The next request is only issued once the response to the current request has been received. As they are affected by network latencies and bandwidth limitations, this can result in significant delay before the next request is *seen* by the server.

Pipelining is the process to send successive requests, over the same persistent connection, without waiting for the answer. This avoids latency of the connection. Theoretically, performance could also be improved if two HTTP requests were to be packed into the same TCP message. The typical MSS (Maximum Segment Size), is big enough to contain several simple requests, although the demand in size of HTTP requests continues to grow.

Not all types of HTTP requests can be pipelined: only idempotent methods, that is `GET`, `HEAD`, `PUT` and `DELETE`, can be replayed safely. Should a failure happen, the pipeline content can be repeated.

Today, every HTTP/1.1-compliant proxy and server should support pipelining, though many have limitations in practice: a significant reason no modern browser activates this feature by default.

Domain sharding
---------------

**Note:** Unless you have a very specific immediate need, don't use this deprecated technique; switch to HTTP/2 instead. In HTTP/2, domain sharding is no longer useful: the HTTP/2 connection is able to handle parallel unprioritized requests very well. Domain sharding is even detrimental to performance. Most HTTP/2 implementations use a technique called connection coalescing to revert eventual domain sharding.

As an HTTP/1.x connection is serializing requests, even without any ordering, it can't be optimal without large enough available bandwidth. As a solution, browsers open several connections to each domain, sending parallel requests. Default was once 2 to 3 connections, but this has now increased to a more common use of 6 parallel connections. There is a risk of triggering DoS protection on the server side if attempting more than this number.

If the server wishes a faster website or application response, it is possible for the server to force the opening of more connections. For example, instead of having all resources on the same domain, say `www.example.com`, it could split over several domains, `www1.example.com`, `www2.example.com`, `www3.example.com`. Each of these domains resolves to the *same* server, and the Web browser will open 6 connections to each (in our example, boosting the connections to 18). This technique is called *domain sharding*.

![Without domain sharding, a client requests six images from a domain with a maximum of two requests taking place in parallel. With domain sharding, the images are available from two domains and the client can run four requests in parallel, downloading the images in less time.](/en-US/docs/Web/HTTP/Connection_management_in_HTTP_1.x/httpsharding.png)

Conclusion
----------

Improved connection management allows considerable boosting of performance in HTTP. With HTTP/1.1 or HTTP/1.0, using a persistent connection – at least until it becomes idle – leads to the best performance. However, the failure of pipelining has lead to designing superior connection management models, which have been incorporated into HTTP/2.


Network Error Logging - HTTP

Network Error Logging
=====================

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

Network Error Logging is a mechanism that can be configured via the `NEL` HTTP *response header*. This experimental header allows websites and applications to opt-in to receive reports about failed (and, if desired, successful) network fetches from supporting browsers.

Reports are sent to a reporting group defined within a `Report-To` header.

Usage
-----

Web applications opt in to this behavior with the NEL header, which is a *JSON-encoded* object:

```http
NEL: { "report\_to": "nel",
 "max\_age": 31556952 }
```

An origin considered secure by the browser is required.

The following object keys can be specified in the NEL header:

report\_to

The reporting API group to send network error reports to (see below).

max\_age

Specifies the lifetime of the policy, in seconds (in a similar way to e.g. HSTS policies are time-restricted). The referenced reporting group should have a lifetime at least as long as the NEL policy.

include\_subdomains

If true, the policy applies to all subdomains under the origin that the policy header is set. The reporting group should also be set to include subdomains, if this option is to be enabled.

success\_fraction

Floating point value between 0 and 1 which specifies the proportion of **successful** network requests to report. Defaults to 0, so that no successful network requests will be reported if the key is not present in the JSON payload.

failure\_fraction

Floating point value between 0 and 1 which specifies the proportion of **failed** network requests to report. Defaults to 1, so that all failed network requests will be reported if the key is not present in the JSON payload.

The reporting group referenced above is defined in the usual manner within the `Report-To` header, for example:

```http
Report-To: { "group": "nel",
 "max\_age": 31556952,
 "endpoints": [
 { "url": "https://example.com/csp-reports" }
 ]
 }
```

Error reports
-------------

In these examples, the entire reporting API payload is shown. The top-level **`"body"`** key contains the network error report.

### HTTP 400 (Bad Request) response

```json
{
  "age": 20,
  "type": "network-error",
  "url": "https://example.com/previous-page",
  "body": {
    "elapsed\_time": 338,
    "method": "POST",
    "phase": "application",
    "protocol": "http/1.1",
    "referrer": "https://example.com/previous-page",
    "sampling\_fraction": 1,
    "server\_ip": "192.0.2.172",
    "status\_code": 400,
    "type": "http.error",
    "url": "https://example.com/bad-request"
  }
}
```

### DNS name not resolved

Note that the phase is set to `dns` in this report and no `server_ip` is available to include.

```json
{
  "age": 20,
  "type": "network-error",
  "url": "https://example.com/previous-page",
  "body": {
    "elapsed\_time": 18,
    "method": "POST",
    "phase": "dns",
    "protocol": "http/1.1",
    "referrer": "https://example.com/previous-page",
    "sampling\_fraction": 1,
    "server\_ip": "",
    "status\_code": 0,
    "type": "dns.name\_not\_resolved",
    "url": "https://example-host.com/"
  }
}
```

The type of the network error may be one of the following pre-defined values from the specification, but browsers can add and send their own error types:

`dns.unreachable`

The user's DNS server is unreachable

`dns.name_not_resolved`

The user's DNS server responded but was unable to resolve an IP address for the requested URI.

`dns.failed`

Request to the DNS server failed due to reasons not covered by previous errors (e.g. SERVFAIL)

`dns.address_changed`

For security reasons, if the server IP address that delivered the original report is different to the current server IP address at time of error generation, the report data will be downgraded to only include information about this problem and the type set to `dns.address_changed`.

`tcp.timed_out`

TCP connection to the server timed out

`tcp.closed`

The TCP connection was closed by the server

`tcp.reset`

The TCP connection was reset

`tcp.refused`

The TCP connection was refused by the server

`tcp.aborted`

The TCP connection was aborted

`tcp.address_invalid`

The IP address is invalid

`tcp.address_unreachable`

The IP address is unreachable

`tcp.failed`

The TCP connection failed due to reasons not covered by previous errors

`http.error`

The user agent successfully received a response, but it had a 4xx or 5xx status code

`http.protocol.error`

The connection was aborted due to an HTTP protocol error

`http.response.invalid`

Response is empty, has a content-length mismatch, has improper encoding, and/or other conditions that prevent user agent from processing the response

`http.response.redirect_loop`

The request was aborted due to a detected redirect loop

`http.failed`

The connection failed due to errors in HTTP protocol not covered by previous errors

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

| Specification |
| --- |
| Network Error Logging # nel-response-header |

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

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


Cross-Origin Resource Sharing (CORS) - HTTP

Cross-Origin Resource Sharing (CORS)
====================================

**Cross-Origin Resource Sharing** (CORS) is an HTTP-header based mechanism that allows a server to indicate any origins (domain, scheme, or port) other than its own from which a browser should permit loading resources. CORS also relies on a mechanism by which browsers make a "preflight" request to the server hosting the cross-origin resource, in order to check that the server will permit the actual request. In that preflight, the browser sends headers that indicate the HTTP method and headers that will be used in the actual request.

An example of a cross-origin request: the front-end JavaScript code served from `https://domain-a.com` uses `fetch()` to make a request for `https://domain-b.com/data.json`.

For security reasons, browsers restrict cross-origin HTTP requests initiated from scripts. For example, `fetch()` and `XMLHttpRequest` follow the same-origin policy. This means that a web application using those APIs can only request resources from the same origin the application was loaded from unless the response from other origins includes the right CORS headers.

![Diagrammatic representation of CORS mechanism](/en-US/docs/Web/HTTP/CORS/cors_principle.png)

The CORS mechanism supports secure cross-origin requests and data transfers between browsers and servers. Browsers use CORS in APIs such as `fetch()` or `XMLHttpRequest` to mitigate the risks of cross-origin HTTP requests.

What requests use CORS?
-----------------------

This cross-origin sharing standard can enable cross-origin HTTP requests for:

* Invocations of `fetch()` or `XMLHttpRequest`, as discussed above.
* Web Fonts (for cross-domain font usage in `@font-face` within CSS), so that servers can deploy TrueType fonts that can only be loaded cross-origin and used by websites that are permitted to do so.
* WebGL textures.
* Images/video frames drawn to a canvas using `drawImage()`.
* CSS Shapes from images.

This is a general article about Cross-Origin Resource Sharing and includes a discussion of the necessary HTTP headers.

Functional overview
-------------------

The Cross-Origin Resource Sharing standard works by adding new HTTP headers that let servers describe which origins are permitted to read that information from a web browser. Additionally, for HTTP request methods that can cause side-effects on server data (in particular, HTTP methods other than `GET`, or `POST` with certain MIME types), the specification mandates that browsers "preflight" the request, soliciting supported methods from the server with the HTTP `OPTIONS` request method, and then, upon "approval" from the server, sending the actual request. Servers can also inform clients whether "credentials" (such as Cookies and HTTP Authentication) should be sent with requests.

CORS failures result in errors but for security reasons, specifics about the error *are not available to JavaScript*. All the code knows is that an error occurred. The only way to determine what specifically went wrong is to look at the browser's console for details.

Subsequent sections discuss scenarios, as well as provide a breakdown of the HTTP headers used.

Examples of access control scenarios
------------------------------------

We present three scenarios that demonstrate how Cross-Origin Resource Sharing works. All these examples use `fetch()`, which can make cross-origin requests in any supporting browser.

### Simple requests

Some requests don't trigger a CORS preflight. Those are called *simple requests* from the obsolete CORS spec, though the Fetch spec (which now defines CORS) doesn't use that term.

The motivation is that the `<form>` element from HTML 4.0 (which predates cross-site `fetch()` and `XMLHttpRequest`) can submit simple requests to any origin, so anyone writing a server must already be protecting against cross-site request forgery (CSRF). Under this assumption, the server doesn't have to opt-in (by responding to a preflight request) to receive any request that looks like a form submission, since the threat of CSRF is no worse than that of form submission. However, the server still must opt-in using `Access-Control-Allow-Origin` to *share* the response with the script.

A *simple request* is one that **meets all the following conditions**:

* One of the allowed methods:
    + `GET`
    + `HEAD`
    + `POST`
* Apart from the headers automatically set by the user agent (for example, `Connection`, `User-Agent`, or the other headers defined in the Fetch spec as a *forbidden header name*), the only headers which are allowed to be manually set are those which the Fetch spec defines as a CORS-safelisted request-header, which are:
    + `Accept`
    + `Accept-Language`
    + `Content-Language`
    + `Content-Type` (please note the additional requirements below)
    + `Range` (only with a simple range header value; e.g., `bytes=256-` or `bytes=127-255`)
* The only type/subtype combinations allowed for the media type specified in the `Content-Type` header are:
    + `application/x-www-form-urlencoded`
    + `multipart/form-data`
    + `text/plain`
* If the request is made using an `XMLHttpRequest` object, no event listeners are registered on the object returned by the `XMLHttpRequest.upload` property used in the request; that is, given an `XMLHttpRequest` instance `xhr`, no code has called `xhr.upload.addEventListener()` to add an event listener to monitor the upload.
* No `ReadableStream` object is used in the request.

**Note:** WebKit Nightly and Safari Technology Preview place additional restrictions on the values allowed in the `Accept`, `Accept-Language`, and `Content-Language` headers. If any of those headers have "nonstandard" values, WebKit/Safari does not consider the request to be a "simple request". What values WebKit/Safari consider "nonstandard" is not documented, except in the following WebKit bugs:

* Require preflight for non-standard CORS-safelisted request headers Accept, Accept-Language, and Content-Language
* Allow commas in Accept, Accept-Language, and Content-Language request headers for simple CORS
* Switch to a blacklist model for restricted Accept headers in simple CORS requests

No other browsers implement these extra restrictions because they're not part of the spec.

For example, suppose web content at `https://foo.example` wishes to fetch JSON content from domain `https://bar.other`. Code of this sort might be used in JavaScript deployed on `foo.example`:

```js
const fetchPromise = fetch("https://bar.other");

fetchPromise
  .then((response) => response.json())
  .then((data) => {
    console.log(data);
  });
```

This operation performs a simple exchange between the client and the server, using CORS headers to handle the privileges:

![Diagram of simple CORS GET request](/en-US/docs/Web/HTTP/CORS/simple-req.png)

Let's look at what the browser will send to the server in this case:

```http
GET /resources/public-data/ HTTP/1.1
Host: bar.other
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:71.0) Gecko/20100101 Firefox/71.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
Origin: https://foo.example
```

The request header of note is `Origin`, which shows that the invocation is coming from `https://foo.example`.

Now let's see how the server responds:

```http
HTTP/1.1 200 OK
Date: Mon, 01 Dec 2008 00:23:53 GMT
Server: Apache/2
Access-Control-Allow-Origin: \*
Keep-Alive: timeout=2, max=100
Connection: Keep-Alive
Transfer-Encoding: chunked
Content-Type: application/xml

[…XML Data…]
```

In response, the server returns a `Access-Control-Allow-Origin` header with `Access-Control-Allow-Origin: *`, which means that the resource can be accessed by **any** origin.

```http
Access-Control-Allow-Origin: \*
```

This pattern of the `Origin` and `Access-Control-Allow-Origin` headers is the simplest use of the access control protocol. If the resource owners at `https://bar.other` wished to restrict access to the resource to requests *only* from `https://foo.example` (i.e., no domain other than `https://foo.example` can access the resource in a cross-origin manner), they would send:

```http
Access-Control-Allow-Origin: https://foo.example
```

**Note:** When responding to a credentialed requests request, the server **must** specify an origin in the value of the `Access-Control-Allow-Origin` header, instead of specifying the "`*`" wildcard.

### Preflighted requests

Unlike *simple requests*, for "preflighted" requests the browser first sends an HTTP request using the `OPTIONS` method to the resource on the other origin, in order to determine if the actual request is safe to send. Such cross-origin requests are preflighted since they may have implications for user data.

The following is an example of a request that will be preflighted:

```js
const fetchPromise = fetch("https://bar.other/doc", {
  method: "POST",
  mode: "cors",
  headers: {
    "Content-Type": "text/xml",
    "X-PINGOTHER": "pingpong",
  },
  body: "<person><name>Arun</name></person>",
});

fetchPromise.then((response) => {
  console.log(response.status);
});
```

The example above creates an XML body to send with the `POST` request. Also, a non-standard HTTP `X-PINGOTHER` request header is set. Such headers are not part of HTTP/1.1, but are generally useful to web applications. Since the request uses a `Content-Type` of `text/xml`, and since a custom header is set, this request is preflighted.

![Diagram of a request that is preflighted](/en-US/docs/Web/HTTP/CORS/preflight_correct.png)

**Note:** As described below, the actual `POST` request does not include the `Access-Control-Request-*` headers; they are needed only for the `OPTIONS` request.

Let's look at the full exchange between client and server. The first exchange is the *preflight request/response*:

```http
OPTIONS /doc HTTP/1.1
Host: bar.other
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:71.0) Gecko/20100101 Firefox/71.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
Origin: https://foo.example
Access-Control-Request-Method: POST
Access-Control-Request-Headers: X-PINGOTHER, Content-Type

HTTP/1.1 204 No Content
Date: Mon, 01 Dec 2008 01:15:39 GMT
Server: Apache/2
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
```

Lines 1 - 10 above represent the preflight request with the `OPTIONS` method. The browser determines that it needs to send this based on the request parameters that the JavaScript code snippet above was using, so that the server can respond whether it is acceptable to send the request with the actual request parameters. OPTIONS is an HTTP/1.1 method that is used to determine further information from servers, and is a safe method, meaning that it can't be used to change the resource. Note that along with the OPTIONS request, two other request headers are sent (lines 9 and 10 respectively):

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

The `Access-Control-Request-Method` header notifies the server as part of a preflight request that when the actual request is sent, it will do so with a `POST` request method. The `Access-Control-Request-Headers` header notifies the server that when the actual request is sent, it will do so with `X-PINGOTHER` and `Content-Type` custom headers. Now the server has an opportunity to determine whether it can accept a request under these conditions.

Lines 12 - 21 above are the response that the server returns, which indicate that the request method (`POST`) and request headers (`X-PINGOTHER`) are acceptable. Let's have a closer look at lines 15-18:

```http
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
```

The server responds with `Access-Control-Allow-Origin: https://foo.example`, restricting access to the requesting origin domain only. It also responds with `Access-Control-Allow-Methods`, which says that `POST` and `GET` are valid methods to query the resource in question (this header is similar to the `Allow` response header, but used strictly within the context of access control).

The server also sends `Access-Control-Allow-Headers` with a value of "`X-PINGOTHER, Content-Type`", confirming that these are permitted headers to be used with the actual request. Like `Access-Control-Allow-Methods`, `Access-Control-Allow-Headers` is a comma-separated list of acceptable headers.

Finally, `Access-Control-Max-Age` gives the value in seconds for how long the response to the preflight request can be cached without sending another preflight request. The default value is 5 seconds. In the present case, the max age is 86400 seconds (= 24 hours). Note that each browser has a maximum internal value that takes precedence when the `Access-Control-Max-Age` exceeds it.

Once the preflight request is complete, the real request is sent:

```http
POST /doc HTTP/1.1
Host: bar.other
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:71.0) Gecko/20100101 Firefox/71.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
X-PINGOTHER: pingpong
Content-Type: text/xml; charset=UTF-8
Referer: https://foo.example/examples/preflightInvocation.html
Content-Length: 55
Origin: https://foo.example
Pragma: no-cache
Cache-Control: no-cache

<person><name>Arun</name></person>

HTTP/1.1 200 OK
Date: Mon, 01 Dec 2008 01:15:40 GMT
Server: Apache/2
Access-Control-Allow-Origin: https://foo.example
Vary: Accept-Encoding, Origin
Content-Encoding: gzip
Content-Length: 235
Keep-Alive: timeout=2, max=99
Connection: Keep-Alive
Content-Type: text/plain

[Some XML payload]
```

#### Preflighted requests and redirects

Not all browsers currently support following redirects after a preflighted request. If a redirect occurs after such a request, some browsers currently will report an error message such as the following:

>
>
>  The request was redirected to 'https://example.com/foo', which is disallowed for cross-origin requests that require preflight.
>  Request requires preflight, which is disallowed to follow cross-origin redirects.
>
>
>
>

The CORS protocol originally required that behavior but was subsequently changed to no longer require it. However, not all browsers have implemented the change, and thus still exhibit the originally required behavior.

Until browsers catch up with the spec, you may be able to work around this limitation by doing one or both of the following:

* Change the server-side behavior to avoid the preflight and/or to avoid the redirect
* Change the request such that it is a simple request that doesn't cause a preflight

If that's not possible, then another way is to:

1. Make a simple request (using `Response.url` for the Fetch API, or `XMLHttpRequest.responseURL`) to determine what URL the real preflighted request would end up at.
2. Make another request (the *real* request) using the URL you obtained from `Response.url` or `XMLHttpRequest.responseURL` in the first step.

However, if the request is one that triggers a preflight due to the presence of the `Authorization` header in the request, you won't be able to work around the limitation using the steps above. And you won't be able to work around it at all unless you have control over the server the request is being made to.

### Requests with credentials

**Note:** When making credentialed requests to a different domain, third-party cookie policies will still apply. The policy is always enforced regardless of any setup on the server and the client as described in this chapter.

The most interesting capability exposed by both `fetch()` or `XMLHttpRequest` and CORS is the ability to make "credentialed" requests that are aware of HTTP cookies and HTTP Authentication information. By default, in cross-origin `fetch()` or `XMLHttpRequest` calls, browsers will *not* send credentials.

To ask for a `fetch()` request to include credentials, set the `credentials` option in the `Request()` constructor to `"include"`.

To ask for an `XMLHttpRequest` request to include credentials, set the `XMLHttpRequest.withCredentials` property to `true`.

In this example, content originally loaded from `https://foo.example` makes a simple GET request to a resource on `https://bar.other` which sets Cookies. Content on foo.example might contain JavaScript like this:

```js
const url = "https://bar.other/resources/credentialed-content/";

const request = new Request(url, { credentials: "include" });

const fetchPromise = fetch(request);
fetchPromise.then((response) => console.log(response));
```

This code creates a `Request` object, setting the `credentials` option to `"include"` in the constructor, then passes this request into `fetch()`. Since this is a simple `GET` request, it is not preflighted but the browser will **reject** any response that does not have the `Access-Control-Allow-Credentials``: true` header, and **not** make the response available to the invoking web content.

![Diagram of a simple GET request with Access-Control-Allow-Credentials](/en-US/docs/Web/HTTP/CORS/cred-req-updated.png)

Here is a sample exchange between client and server:

```http
GET /resources/credentialed-content/ HTTP/1.1
Host: bar.other
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:71.0) Gecko/20100101 Firefox/71.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
Referer: https://foo.example/examples/credential.html
Origin: https://foo.example
Cookie: pageAccess=2

HTTP/1.1 200 OK
Date: Mon, 01 Dec 2008 01:34:52 GMT
Server: Apache/2
Access-Control-Allow-Origin: https://foo.example
Access-Control-Allow-Credentials: true
Cache-Control: no-cache
Pragma: no-cache
Set-Cookie: pageAccess=3; expires=Wed, 31-Dec-2008 01:34:53 GMT
Vary: Accept-Encoding, Origin
Content-Encoding: gzip
Content-Length: 106
Keep-Alive: timeout=2, max=100
Connection: Keep-Alive
Content-Type: text/plain

[text/plain payload]
```

Although line 10 contains the Cookie destined for the content on `https://bar.other`, if bar.other did not respond with an `Access-Control-Allow-Credentials``: true` (line 16), the response would be ignored and not made available to the web content.

#### Preflight requests and credentials

CORS-preflight requests must never include credentials. The *response* to a preflight request must specify `Access-Control-Allow-Credentials: true` to indicate that the actual request can be made with credentials.

**Note:** Some enterprise authentication services require that TLS client certificates be sent in preflight requests, in contravention of the Fetch specification.

Firefox 87 allows this non-compliant behavior to be enabled by setting the preference: `network.cors_preflight.allow_client_cert` to `true` (Firefox bug 1511151). Chromium-based browsers currently always send TLS client certificates in CORS preflight requests (Chrome bug 775438).

#### Credentialed requests and wildcards

When responding to a credentialed request:

* The server **must not** specify the "`*`" wildcard for the `Access-Control-Allow-Origin` response-header value, but must instead specify an explicit origin; for example: `Access-Control-Allow-Origin: https://example.com`
* The server **must not** specify the "`*`" wildcard for the `Access-Control-Allow-Headers` response-header value, but must instead specify an explicit list of header names; for example, `Access-Control-Allow-Headers: X-PINGOTHER, Content-Type`
* The server **must not** specify the "`*`" wildcard for the `Access-Control-Allow-Methods` response-header value, but must instead specify an explicit list of method names; for example, `Access-Control-Allow-Methods: POST, GET`
* The server **must not** specify the "`*`" wildcard for the `Access-Control-Expose-Headers` response-header value, but must instead specify an explicit list of header names; for example, `Access-Control-Expose-Headers: Content-Encoding, Kuma-Revision`

If a request includes a credential (most commonly a `Cookie` header) and the response includes an `Access-Control-Allow-Origin: *` header (that is, with the wildcard), the browser will block access to the response, and report a CORS error in the devtools console.

But if a request does include a credential (like the `Cookie` header) and the response includes an actual origin rather than the wildcard (like, for example, `Access-Control-Allow-Origin: https://example.com`), then the browser will allow access to the response from the specified origin.

Also note that any `Set-Cookie` response header in a response would not set a cookie if the `Access-Control-Allow-Origin` value in that response is the "`*`" wildcard rather an actual origin.

#### Third-party cookies

Note that cookies set in CORS responses are subject to normal third-party cookie policies. In the example above, the page is loaded from `foo.example` but the cookie on line 19 is sent by `bar.other`, and would thus not be saved if the user's browser is configured to reject all third-party cookies.

Cookie in the request (line 10) may also be suppressed in normal third-party cookie policies. The enforced cookie policy may therefore nullify the capability described in this chapter, effectively preventing you from making credentialed requests whatsoever.

Cookie policy around the SameSite attribute would apply.

The HTTP response headers
-------------------------

This section lists the HTTP response headers that servers return for access control requests as defined by the Cross-Origin Resource Sharing specification. The previous section gives an overview of these in action.

### Access-Control-Allow-Origin

A returned resource may have one `Access-Control-Allow-Origin` header with the following syntax:

```http
Access-Control-Allow-Origin: <origin> | \*
```

`Access-Control-Allow-Origin` specifies either a single origin which tells browsers to allow that origin to access the resource; or else — for requests **without** credentials — the "`*`" wildcard tells browsers to allow any origin to access the resource.

For example, to allow code from the origin `https://mozilla.org` to access the resource, you can specify:

```http
Access-Control-Allow-Origin: https://mozilla.org
Vary: Origin
```

If the server specifies a single origin (that may dynamically change based on the requesting origin as part of an allowlist) rather than the "`*`" wildcard, then the server should also include `Origin` in the `Vary` response header to indicate to clients that server responses will differ based on the value of the `Origin` request header.

### Access-Control-Expose-Headers

The `Access-Control-Expose-Headers` header adds the specified headers to the allowlist that JavaScript (such as `Response.headers`) in browsers is allowed to access.

```http
Access-Control-Expose-Headers: <header-name>[, <header-name>]\*
```

For example, the following:

```http
Access-Control-Expose-Headers: X-My-Custom-Header, X-Another-Custom-Header
```

…would allow the `X-My-Custom-Header` and `X-Another-Custom-Header` headers to be exposed to the browser.

### Access-Control-Max-Age

The `Access-Control-Max-Age` header indicates how long the results of a preflight request can be cached. For an example of a preflight request, see the above examples.

```http
Access-Control-Max-Age: <delta-seconds>
```

The `delta-seconds` parameter indicates the number of seconds the results can be cached.

### Access-Control-Allow-Credentials

The `Access-Control-Allow-Credentials` header indicates whether or not the response to the request can be exposed when the `credentials` flag is true. When used as part of a response to a preflight request, this indicates whether or not the actual request can be made using credentials. Note that simple `GET` requests are not preflighted, and so if a request is made for a resource with credentials, if this header is not returned with the resource, the response is ignored by the browser and not returned to web content.

```http
Access-Control-Allow-Credentials: true
```

Credentialed requests are discussed above.

### Access-Control-Allow-Methods

The `Access-Control-Allow-Methods` header specifies the method or methods allowed when accessing the resource. This is used in response to a preflight request. The conditions under which a request is preflighted are discussed above.

```http
Access-Control-Allow-Methods: <method>[, <method>]\*
```

An example of a preflight request is given above, including an example which sends this header to the browser.

### Access-Control-Allow-Headers

The `Access-Control-Allow-Headers` header is used in response to a preflight request to indicate which HTTP headers can be used when making the actual request. This header is the server side response to the browser's `Access-Control-Request-Headers` header.

```http
Access-Control-Allow-Headers: <header-name>[, <header-name>]\*
```

The HTTP request headers
------------------------

This section lists headers that clients may use when issuing HTTP requests in order to make use of the cross-origin sharing feature. Note that these headers are set for you when making invocations to servers. Developers making cross-origin requests do not have to set any cross-origin sharing request headers programmatically.

### Origin

The `Origin` header indicates the origin of the cross-origin access request or preflight request.

```http
Origin: <origin>
```

The origin is a URL indicating the server from which the request is initiated. It does not include any path information, only the server name.

**Note:** The `origin` value can be `null`.

Note that in any access control request, the `Origin` header is **always** sent.

### Access-Control-Request-Method

The `Access-Control-Request-Method` is used when issuing a preflight request to let the server know what HTTP method will be used when the actual request is made.

```http
Access-Control-Request-Method: <method>
```

Examples of this usage can be found above.

### Access-Control-Request-Headers

The `Access-Control-Request-Headers` header is used when issuing a preflight request to let the server know what HTTP headers will be used when the actual request is made (for example, by passing them as the `headers` option to the `Request()` constructor). This browser-side header will be answered by the complementary server-side header of `Access-Control-Allow-Headers`.

```http
Access-Control-Request-Headers: <field-name>[, <field-name>]\*
```

Examples of this usage can be found above.

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

| Specification |
| --- |
| Fetch Standard # http-access-control-allow-origin |

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

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

See also
--------

* CORS errors
* Enable CORS: I want to add CORS support to my server
* Fetch API
* `XMLHttpRequest`
* Will it CORS? - an interactive CORS explainer & generator
* How to run Chrome browser without CORS
* Using CORS with All (Modern) Browsers
* Stack Overflow answer with "how to" info for dealing with common problems:
    + How to avoid the CORS preflight
    + How to use a CORS proxy to get around *"No Access-Control-Allow-Origin header"*
    + How to fix *"Access-Control-Allow-Origin header must not be the wildcard"*


Content negotiation - HTTP

Content negotiation
===================

In HTTP, ***content negotiation*** is the mechanism that is used for serving different representations of a resource to the same URI to help the user agent specify which representation is best suited for the user (for example, which document language, which image format, or which content encoding).

**Note:** You'll find some disadvantages of HTTP content negotiation in a wiki page from WHATWG. HTML provides alternatives to content negotiation via, for example, the `<source>` element.

Principles of content negotiation
---------------------------------

A specific document is called a *resource*. When a client wants to obtain a resource, the client requests it via a URL. The server uses this URL to choose one of the variants available–each variant is called a *representation*–and returns a specific representation to the client. The overall resource, as well as each of the representations, has a specific URL. *Content negotiation* determines how a specific representation is chosen when the resource is called. There are several ways of negotiating between the client and the server.

![A client requesting a URL. The server has multiple resources represented by the URL and sends back appropriate content based on the request.](/en-US/docs/Web/HTTP/Content_negotiation/httpnego.png)

The best-suited representation is identified through one of two mechanisms:

* Specific HTTP headers by the client (*server-driven negotiation* or *proactive negotiation*), which is the standard way of negotiating a specific kind of resource.
* The `300` (Multiple Choices) or `406` (Not Acceptable), `415` (Unsupported Media Type) HTTP response codes by the server (*agent-driven negotiation* or *reactive negotiation*), that are used as fallback mechanisms.

Over the years, other content negotiation proposals, like transparent content negotiation and the `Alternates` header, have been proposed. They failed to get traction and were abandoned.

Server-driven content negotiation
---------------------------------

In *server-driven content negotiation*, or proactive content negotiation, the browser (or any other kind of user agent) sends several HTTP headers along with the URL. These headers describe the user's preferred choice. The server uses them as hints and an internal algorithm chooses the best content to serve to the client. If it can't provide a suitable resource, it might respond with `406` (Not Acceptable) or `415` (Unsupported Media Type) and set headers for the types of media that it does support (e.g., using the `Accept-Post` or `Accept-Patch` for POST and PATCH requests, respectively). The algorithm is server-specific and not defined in the standard. See the Apache negotiation algorithm.

![A client requesting a URL with headers denoting a preference for content types. The server has multiple resources represented by the URL and sends back the content for the preferred language and compresses the request body based, respecting the client's request headers.](/en-US/docs/Web/HTTP/Content_negotiation/httpnegoserver.png)

The HTTP/1.1 standard defines list of the standard headers that start server-driven negotiation (such as `Accept`, `Accept-Encoding`, and `Accept-Language`). Though `User-Agent` isn't in this list, it's sometimes also used to send a specific representation of the requested resource. However, this isn't always considered a good practice. The server uses the `Vary` header to indicate which headers it actually used for content negotiation (or more precisely, the associated request headers), so that caches can work optimally.

In addition to these, there's an experimental proposal to add more headers to the list of available headers, called *client hints*. Client hints advertise what kind of device the user agent runs on (for example, a desktop computer or a mobile device).

Even if server-driven content negotiation is the most common way to agree on a specific representation of a resource, it has several drawbacks:

* The server doesn't have total knowledge of the browser. Even with the Client Hints extension, it doesn't have a complete knowledge of the capabilities of the browser. Unlike reactive content negotiation where the client makes the choice, the server choice is always somewhat arbitrary.
* The information from the client is quite verbose (HTTP/2 header compression mitigates this problem) and a privacy risk (HTTP fingerprinting).
* As several representations of a given resource are sent, shared caches are less efficient and server implementations are more complex.
### The `Accept` header

The `Accept` header lists the MIME types of media resources that the agent is willing to process. This is a comma-separated list of MIME types, each combined with a quality factor, a parameter that indicates the relative degree of preference between the different MIME types.

The `Accept` header is defined by the browser, or any other user agent, and can vary according to the context. For example, fetching an HTML page or an image, a video, or a script. It's different when fetching a document entered in the address bar or an element linked via an `<img>`, `<video>`, or `<audio>` element. Browsers are free to use the value of the header that they think is the most adequate; an exhaustive list of default values for common browsers is available.

### The `Accept-CH` header
Experimental

**Note:** This is part of an **experimental** technology called *Client Hints*. Initial support comes in Chrome 46 or later. The Device-Memory value is in Chrome 61 or later.

The experimental `Accept-CH` lists configuration data that the server can use to select an appropriate response. Valid values are:

| Value | Meaning |
| --- | --- |
| `Device-Memory` | Indicates the approximate amount of device RAM. This value is an approximation given by rounding to the nearest power of 2 and dividing that number by 1024. For example, 512 megabytes will be reported as `0.5`. |
| `Viewport-Width` | Indicates the layout viewport width in CSS pixels. |
| `Width` | Indicates the resource width in physical pixels (in other words the intrinsic size of an image). |

### The `Accept-CH-Lifetime` header

**Note:** This is part of an **experimental** technology called *Client Hints* and is only available in Chrome 61 or later.

The `Accept-CH-Lifetime` header is used with the `Device-Memory` value of the `Accept-CH` header and indicates the amount of time the device should opt in to sharing the device memory with the server. The value is given in milliseconds and it's optional.

### The `Accept-Encoding` header

The `Accept-Encoding` header defines the acceptable content encoding (supported compressions). The value is a q-factor list (e.g., `br, gzip;q=0.8`) that indicates the priority of the encoding values. The default value `identity` is at the lowest priority (unless otherwise noted).

Compressing HTTP messages is one of the most important ways to improve the performance of a website. It shrinks the size of the data transmitted and makes better use of the available bandwidth. Browsers always send this header and the server should be configured to use compression.

### The `Accept-Language` header

The `Accept-Language` header is used to indicate the language preference of the user. It's a list of values with quality factors (e.g., `"de, en;q=0.7`"). A default value is often set according to the language of the graphical interface of the user agent, but most browsers allow different language preferences to be set.

Due to the configuration-based entropy increase, a modified value can be used to fingerprint the user. It's not recommended to change it and a website can't trust this value to reflect the actual intention of the user. It's best for site designers to avoid using language detection via this header as it can lead to a poor user experience.

* They should always provide a way to override the server-chosen language, e.g., by providing a language menu on the site. Most user agents provide a default value for the `Accept-Language` header that's adapted to the user interface language. End users often don't modify it because they either don't know how or aren't able to do so based on their computing environment.
* Once a user has overridden the server-chosen language, a site should no longer use language detection and should stick with the explicitly chosen language. In other words, only entry pages for a site should use this header to select the proper language.
### The `User-Agent` header

**Note:** Though there are legitimate uses of this header for selecting content, it's considered bad practice to rely on it to define what features are supported by the user agent.

The `User-Agent` header identifies the browser sending the request. This string may contain a space-separated list of *product tokens* and *comments*.

A *product token* is a name followed by a '`/`' and a version number, like `Firefox/4.0.1`. The user agent can include as many of these as it wants. A *comment* is an optional string delimited by parentheses. The information provided in a comment isn't standardized, though several browsers add several tokens to it separated by '`;`'.

### The `Vary` response header

In contrast to the previous `Accept-*` headers, which are sent by the client, the `Vary` HTTP header is sent by the web server in its response. It indicates the list of headers the server uses during the server-driven content negotiation phase. The `Vary` header is needed to inform the cache of the decision criteria so that it can reproduce it. This allows the cache to be functional while ensuring that the right content is served to the user.

The special value '`*`' means that the server-driven content negotiation also uses information not conveyed in a header to choose the appropriate content.

The `Vary` header was added in version 1.1 of HTTP and allows caches to work appropriately. To work with server-driven content negotiation, a cache needs to know which criteria the server used to select the transmitted content. That way, the cache can replay the algorithm and will be able to serve acceptable content directly, without more requests to the server. Obviously, the wildcard '`*`' prevents caching from occurring, as the cache can't know what element is behind it. For more information, see HTTP caching > Varying responses.

Agent-driven negotiation
------------------------

Server-driven negotiation has a few drawbacks: it doesn't scale well. One header per feature is used in the negotiation. If you want to use screen size, resolution, or other dimensions, you need to create a new HTTP header. The headers must then be sent with every request. This isn't an issue if there are only a few headers, but as the number of headers increases, the message size could eventually affect performance. The more precisely headers are sent, the more entropy is sent, allowing for more HTTP fingerprinting and corresponding privacy concerns.

HTTP allows another negotiation type: *agent-driven negotiation* or *reactive negotiation*. In this case, the server sends back a page that contains links to the available alternative resources when faced with an ambiguous request. The user is presented the resources and chooses the one to use.

![A client requesting a URL with headers denoting a preference for content types. The server has multiple resources represented by the URL and sends back multiple responses so the client may choose a body with a preferred compression algorithms applied.](/en-US/docs/Web/HTTP/Content_negotiation/httpnego3.png)

Unfortunately, the HTTP standard doesn't specify the format of the page for choosing between the available resources, which prevents the process from being automated. Besides falling back to the *server-driven negotiation*, this method is almost always used with scripting, especially with JavaScript redirection: after having checked for the negotiation criteria, the script performs the redirection. A second problem is that one more request is needed to fetch the real resource, slowing the availability of the resource to the user.


Basics of HTTP - HTTP

Basics of HTTP
==============

HTTP is an extensible protocol that relies on concepts like resources and Uniform Resource Identifiers (URIs), simple message structure, and client-server communication flow. On top of these basic concepts, numerous extensions have been developed over the years that add updated functionality and semantics with new HTTP methods or headers.

Articles
--------

Overview of HTTP

Describes what HTTP is and its role in web architecture, including its position in the protocol stack.

Evolution of HTTP

HTTP was created in the early 1990s and has been extended several times. This article goes through its history and describes HTTP/0.9, HTTP/1.0, HTTP/1.1, and the modern HTTP/2, as well as novelties introduced over the years.

Resources and URIs

A brief introduction to the concept of resources, identifiers, and locations on the web.

Identifying resources on the Web

Describes how web resources are referenced and how to locate them.

Data URLs

A specific kind of URI that directly embeds the resource it represents. Data URLs are very convenient, but have some caveats.

Resource URLs
Non-standard

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

MIME types

Since HTTP/1.0, different types of content can be transmitted. This article explains how this is accomplished using the `Content-Type` header and the MIME standard.

Choosing between www and non-www URLs

This article provides guidance on how to choose whether to use a www-prefixed domain or not, along with the consequences of that choice.

Flow of an HTTP session

This article describes a typical HTTP session; i.e. what happens when you follow a link or load an image into a web page.

HTTP Messages

HTTP Messages transmitted during requests or responses have a very clear structure. This introductory article describes this structure, its purpose, and its possibilities.

Frame and message structure in HTTP/2

HTTP/2 encapsulates and represents HTTP/1.x messages in a binary frame. This article explains the frame structure, its purpose, and the way it's encoded.

Connection management in HTTP/1.x

HTTP/1.1 was the first version of HTTP to support persistent connection and pipelining. This article explains both concepts.

Connection management in HTTP/2

HTTP/2 completely revisited how connections are created and maintained. This article explains how HTTP frames allow multiplexing and solve the 'head-of-line' blocking problem of former HTTP versions.

Content Negotiation

HTTP introduces a set of headers, starting with `Accept` as a way for a browser to announce the format, language, or encoding it prefers. This article explains how this advertisement happens, how the server is expected to react, and how it chooses the most adequate response.


List of default Accept values - HTTP

List of default Accept values
=============================

This article documents the default values for the HTTP `Accept` header for specific inputs and browser versions.

Default values
--------------

These are the values sent when the context doesn't give better information. Note that all browsers add the `*/*` MIME Type to cover all cases. This is typically used for requests initiated via the address bar of a browser, or via an HTML `<a>` element.

| User Agent | Value |
| --- | --- |
| Firefox 92 and later [1] | `text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8` |
| Firefox 72 to 91 [1] | `text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8` |
| Firefox 66 to 71 [1] | `text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8` |
| Firefox 65 [1] | `text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8` |
| Firefox 64 and earlier [1] | `text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8` |
| Safari, Chrome | `text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8` |
| Safari 5 [2] | `text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8` |
| Edge | `text/html, application/xhtml+xml, image/jxr, */*` |
| Opera | `text/html, application/xml;q=0.9, application/xhtml+xml, image/png, image/webp, image/jpeg, image/gif, image/x-xbitmap, */*;q=0.1` |

[1] This value can be modified using the `network.http.accept.default` parameter.

[2] This is an improvement over earlier `Accept` headers as it no longer ranks `image/png` above `text/html`.

Values for an image
-------------------

When requesting an image, like through an HTML `<img>` element, user-agent often sets a specific list of media types to be welcomed.

| User Agent | Value |
| --- | --- |
| Firefox 92 and later [1] | `image/avif,image/webp,*/*` |
| Firefox 65 to 91 [1] | `image/webp,*/*` |
| Firefox 47 to 63 [1] | `*/*` |
| Firefox prior to 47 [1] | `image/png,image/*;q=0.8,*/*;q=0.5` |
| Safari (since Mac OS Big Sur) | `image/webp,image/png,image/svg+xml,image/*;q=0.8,video/*;q=0.8,*/*;q=0.5` |
| Safari (before Mac OS Big Sur) | `image/png,image/svg+xml,image/*;q=0.8,video/*;q=0.8,*/*;q=0.5` |
| Chrome and Edge 121 and later | `image/avif,image/webp,image/apng,image/*,*/*;q=0.8` |

[1] This value can be modified using the `image.http.accept` parameter (*source*).

Values for a video
------------------

When a video is requested, via the `<video>` HTML element, most browsers use specific values.

| User Agent | Value |
| --- | --- |
| Firefox 3.6 and later | `video/webm,video/ogg,video/*;q=0.9,application/ogg;q=0.7,audio/*;q=0.6,*/*;q=0.5` |
| Firefox earlier than 3.6 | *no support for `<video>`* |
| Chrome | `*/*` |

Values for audio resources
--------------------------

When an audio file is requested, like via the `<audio>` HTML element, most browsers use specific values.

| User Agent | Value |
| --- | --- |
| Firefox 3.6 and later [1] | `audio/webm,audio/ogg,audio/wav,audio/*;q=0.9,application/ogg;q=0.7,video/*;q=0.6,*/*;q=0.5` |
| Safari, Chrome | `*/*` |

[1] See bug 489071.

Values for scripts
------------------

When a script is requested, like via the `<script>` HTML element, some browsers use specific values.

| User Agent | Value |
| --- | --- |
| Firefox [1] | `*/*` |
| Safari, Chrome | `*/*` |

[1] See bug 170789.

Values for a CSS stylesheet
---------------------------

When a CSS stylesheet is requested, via the `<link rel="stylesheet">` HTML element, most browsers use specific values.

| User Agent | Value |
| --- | --- |
| Firefox 4 [1] | `text/css,*/*;q=0.1` |
| Safari, Chrome | `text/css,*/*;q=0.1` |
| Opera 11.10 | `text/html, application/xml;q=0.9, application/xhtml+xml, image/png, image/webp, image/jpeg, image/gif, image/x-xbitmap, */*;q=0.1` |
| Konqueror 4.6 | `text/css,*/*;q=0.1` |

[1] See bug 170789.