http headers | overview

Using FETCH Api to send in reactOverviewall http headers

https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

 

Try this

fetch('your_url', { 
   method: 'get', 
   headers: new Headers({
     // Your header content
   })
 });

 

 

 

You can just pass them into fetch():

const API = 'foo';

fetch(API, { headers: {
  'user-agent': 'Mozilla/4.0 MDN Example',
  'content-type': 'application/json'
}}).then()

You can read more on that here.

 


 

 

 

 

Using the Fetch API

The Fetch API provides a JavaScript interface for accessing and manipulating parts of the HTTP pipeline, such as requests and responses. It also provides a global fetch() method that provides an easy, logical way to fetch resources asynchronously across the network.

This kind of functionality was previously achieved using XMLHttpRequest. Fetch provides a better alternative that can be easily used by other technologies such as Service Workers. Fetch also provides a single logical place to define other HTTP-related concepts such as CORS and extensions to HTTP.

The fetch specification differs from jQuery.ajax() in the following significant ways:

  • The Promise returned from fetch() won't reject on HTTP error status even if the response is an HTTP 404 or 500. Instead, as soon as the server responds with headers, the Promise will resolve normally (with the ok property of the response set to false if the response isn't in the range 200–299), and it will only reject on network failure or if anything prevented the request from completing.

  • Unless

    fetch()
    

    is called with the

    credentials

    option set to

    include
    

    ,

    fetch()
    

    :

    • won't send cookies in cross-origin requests
    • won’t set any cookies sent back in cross-origin responses

A basic fetch request is really simple to set up. Have a look at the following code:

fetch('http://example.com/movies.json')
  .then(response => response.json())
  .then(data => console.log(data));

Copy to Clipboard

Here we are fetching a JSON file across the network and printing it to the console. The simplest use of fetch() takes one argument — the path to the resource you want to fetch — and does not directly return the JSON response body but instead returns a promise that resolves with a Response object.

The Response object, in turn, does not directly contain the actual JSON response body but is instead a representation of the entire HTTP response. So, to extract the JSON body content from the Response object, we use the json() method, which returns a second promise that resolves with the result of parsing the response body text as JSON.

Note: See the Body section for similar methods to extract other types of body content.

Fetch requests are controlled by the connect-src directive of Content Security Policy rather than the directive of the resources it's retrieving.

Supplying request options

The fetch() method can optionally accept a second parameter, an init object that allows you to control a number of different settings:

See fetch() for the full options available, and more details.

// Example POST method implementation:
async function postData(url = '', data = {}) {
  // Default options are marked with *
  const response = await fetch(url, {
    method: 'POST', // *GET, POST, PUT, DELETE, etc.
    mode: 'cors', // no-cors, *cors, same-origin
    cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
    credentials: 'same-origin', // include, *same-origin, omit
    headers: {
      'Content-Type': 'application/json'
      // 'Content-Type': 'application/x-www-form-urlencoded',
    },
    redirect: 'follow', // manual, *follow, error
    referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
    body: JSON.stringify(data) // body data type must match "Content-Type" header
  });
  return response.json(); // parses JSON response into native JavaScript objects
}

postData('https://example.com/answer', { answer: 42 })
  .then(data => {
    console.log(data); // JSON data parsed by `data.json()` call
  });

Copy to Clipboard

Note that mode: "no-cors" only allows a limited set of headers in the request:

  • Accept
  • Accept-Language
  • Content-Language
  • Content-Type with a value of application/x-www-form-urlencoded, multipart/form-data, or text/plain

Sending a request with credentials included

To cause browsers to send a request with credentials included on both same-origin and cross-origin calls, add credentials: 'include' to the init object you pass to the fetch() method.

fetch('https://example.com', {
  credentials: 'include'
});

Copy to Clipboard

Note: Access-Control-Allow-Origin is prohibited from using a wildcard for requests with credentials: 'include'. In such cases, the exact origin must be provided; even if you are using a CORS unblocker extension, the requests will still fail.

Note: Browsers should not send credentials in preflight requests irrespective of this setting. For more information see: CORS > Requests with credentials.

If you only want to send credentials if the request URL is on the same origin as the calling script, add credentials: 'same-origin'.

// The calling script is on the origin 'https://example.com'

fetch('https://example.com', {
  credentials: 'same-origin'
});

Copy to Clipboard

To instead ensure browsers don't include credentials in the request, use credentials: 'omit'.

fetch('https://example.com', {
  credentials: 'omit'
})

Copy to Clipboard

Uploading JSON data

Use fetch() to POST JSON-encoded data.

const data = { username: 'example' };

fetch('https://example.com/profile', {
  method: 'POST', // or 'PUT'
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify(data),
})
.then(response => response.json())
.then(data => {
  console.log('Success:', data);
})
.catch((error) => {
  console.error('Error:', error);
});

Copy to Clipboard

Uploading a file

Files can be uploaded using an HTML <input type="file" /> input element, FormData() and fetch().

const formData = new FormData();
const fileField = document.querySelector('input[type="file"]');

formData.append('username', 'abc123');
formData.append('avatar', fileField.files[0]);

fetch('https://example.com/profile/avatar', {
  method: 'PUT',
  body: formData
})
.then(response => response.json())
.then(result => {
  console.log('Success:', result);
})
.catch(error => {
  console.error('Error:', error);
});

Copy to Clipboard

Uploading multiple files

Files can be uploaded using an HTML <input type="file" multiple /> input element, FormData() and fetch().

const formData = new FormData();
const photos = document.querySelector('input[type="file"][multiple]');

formData.append('title', 'My Vegas Vacation');
for (let i = 0; i < photos.files.length; i++) {
  formData.append(`photos_${i}`, photos.files[i]);
}

fetch('https://example.com/posts', {
  method: 'POST',
  body: formData,
})
.then(response => response.json())
.then(result => {
  console.log('Success:', result);
})
.catch(error => {
  console.error('Error:', error);
});

Copy to Clipboard

Processing a text file line by line

The chunks that are read from a response are not broken neatly at line boundaries and are Uint8Arrays, not strings. If you want to fetch a text file and process it line by line, it is up to you to handle these complications. The following example shows one way to do this by creating a line iterator (for simplicity, it assumes the text is UTF-8, and doesn't handle fetch errors).

async function* makeTextFileLineIterator(fileURL) {
  const utf8Decoder = new TextDecoder('utf-8');
  const response = await fetch(fileURL);
  const reader = response.body.getReader();
  let { value: chunk, done: readerDone } = await reader.read();
  chunk = chunk ? utf8Decoder.decode(chunk) : '';

  const re = /\n|\r|\r\n/gm;
  let startIndex = 0;
  let result;

  for (;;) {
    let result = re.exec(chunk);
    if (!result) {
      if (readerDone) {
        break;
      }
      let remainder = chunk.substr(startIndex);
      ({ value: chunk, done: readerDone } = await reader.read());
      chunk = remainder + (chunk ? utf8Decoder.decode(chunk) : '');
      startIndex = re.lastIndex = 0;
      continue;
    }
    yield chunk.substring(startIndex, result.index);
    startIndex = re.lastIndex;
  }
  if (startIndex < chunk.length) {
    // last line didn't end in a newline char
    yield chunk.substr(startIndex);
  }
}

async function run() {
  for await (let line of makeTextFileLineIterator(urlOfFile)) {
    processLine(line);
  }
}

run();

Copy to Clipboard

Checking that the fetch was successful

A fetch() promise will reject with a TypeError when a network error is encountered or CORS is misconfigured on the server-side, although this usually means permission issues or similar — a 404 does not constitute a network error, for example. An accurate check for a successful fetch() would include checking that the promise resolved, then checking that the Response.ok property has a value of true. The code would look something like this:

fetch('flowers.jpg')
  .then(response => {
    if (!response.ok) {
      throw new Error('Network response was not OK');
    }
    return response.blob();
  })
  .then(myBlob => {
    myImage.src = URL.createObjectURL(myBlob);
  })
  .catch(error => {
    console.error('There has been a problem with your fetch operation:', error);
  });

Copy to Clipboard

Supplying your own request object

Instead of passing a path to the resource you want to request into the fetch() call, you can create a request object using the Request() constructor, and pass that in as a fetch() method argument:

const myHeaders = new Headers();

const myRequest = new Request('flowers.jpg', {
  method: 'GET',
  headers: myHeaders,
  mode: 'cors',
  cache: 'default',
});

fetch(myRequest)
  .then(response => response.blob())
  .then(myBlob => {
    myImage.src = URL.createObjectURL(myBlob);
  });

Copy to Clipboard

Request() accepts exactly the same parameters as the fetch() method. You can even pass in an existing request object to create a copy of it:

const anotherRequest = new Request(myRequest, myInit);

Copy to Clipboard

This is pretty useful, as request and response bodies can only be used once. Making a copy like this allows you to effectively use the request/response again while varying the init options if desired. The copy must be made before the body is read.

Note: There is also a clone() method that creates a copy. Both methods of creating a copy will fail if the body of the original request or response has already been read, but reading the body of a cloned response or request will not cause it to be marked as read in the original.

Headers

The Headers interface allows you to create your own headers object via the Headers() constructor. A headers object is a simple multi-map of names to values:

const content = 'Hello World';
const myHeaders = new Headers();
myHeaders.append('Content-Type', 'text/plain');
myHeaders.append('Content-Length', content.length.toString());
myHeaders.append('X-Custom-Header', 'ProcessThisImmediately');

Copy to Clipboard

The same can be achieved by passing an array of arrays or an object literal to the constructor:

const myHeaders = new Headers({
  'Content-Type': 'text/plain',
  'Content-Length': content.length.toString(),
  'X-Custom-Header': 'ProcessThisImmediately'
});

Copy to Clipboard

The contents can be queried and retrieved:

console.log(myHeaders.has('Content-Type')); // true
console.log(myHeaders.has('Set-Cookie')); // false
myHeaders.set('Content-Type', 'text/html');
myHeaders.append('X-Custom-Header', 'AnotherValue');

console.log(myHeaders.get('Content-Length')); // 11
console.log(myHeaders.get('X-Custom-Header')); // ['ProcessThisImmediately', 'AnotherValue']

myHeaders.delete('X-Custom-Header');
console.log(myHeaders.get('X-Custom-Header')); // null

Copy to Clipboard

Some of these operations are only useful in ServiceWorkers, but they provide a much nicer API for manipulating headers.

All of the Headers methods throw a TypeError if a header name is used that is not a valid HTTP Header name. The mutation operations will throw a TypeError if there is an immutable guard (see below). Otherwise, they fail silently. For example:

const myResponse = Response.error();
try {
  myResponse.headers.set('Origin', 'http://mybank.com');
} catch (e) {
  console.log('Cannot pretend to be a bank!');
}

Copy to Clipboard

A good use case for headers is checking whether the content type is correct before you process it further. For example:

fetch(myRequest)
  .then(response => {
     const contentType = response.headers.get('content-type');
     if (!contentType || !contentType.includes('application/json')) {
       throw new TypeError("Oops, we haven't got JSON!");
     }
     return response.json();
  })
  .then(data => {
      /* process your data further */
  })
  .catch(error => console.error(error));

Copy to Clipboard

Guard

Since headers can be sent in requests and received in responses, and have various limitations about what information can and should be mutable, headers' objects have a guard property. This is not exposed to the Web, but it affects which mutation operations are allowed on the headers object.

Possible guard values are:

  • none: default.
  • request: guard for a headers object obtained from a request (Request.headers).
  • request-no-cors: guard for a headers object obtained from a request created with Request.mode no-cors.
  • response: guard for a headers object obtained from a response (Response.headers).
  • immutable: guard that renders a headers object read-only; mostly used for ServiceWorkers.

Note: You may not append or set the Content-Length header on a guarded headers object for a response. Similarly, inserting Set-Cookie into a response header is not allowed: ServiceWorkers are not allowed to set cookies via synthesized responses.

Response objects

As you have seen above, Response instances are returned when fetch() promises are resolved.

The most common response properties you'll use are:

  • Response.status — An integer (default value 200) containing the response status code.
  • Response.statusText — A string (default value ""), which corresponds to the HTTP status code message. Note that HTTP/2 does not support status messages.
  • Response.ok — seen in use above, this is a shorthand for checking that status is in the range 200-299 inclusive. This returns a boolean value.

They can also be created programmatically via JavaScript, but this is only really useful in ServiceWorkers, when you are providing a custom response to a received request using a respondWith() method:

const myBody = new Blob();

addEventListener('fetch', function(event) {
  // ServiceWorker intercepting a fetch
  event.respondWith(
    new Response(myBody, {
      headers: { 'Content-Type': 'text/plain' }
    })
  );
});

Copy to Clipboard

The Response() constructor takes two optional arguments — a body for the response, and an init object (similar to the one that Request() accepts.)

Note: The static method error() returns an error response. Similarly, redirect() returns a response resulting in a redirect to a specified URL. These are also only relevant to Service Workers.

Body

Both requests and responses may contain body data. A body is an instance of any of the following types:

The Request and Response interfaces share the following methods to extract a body. These all return a promise that is eventually resolved with the actual content.

This makes usage of non-textual data much easier than it was with XHR.

Request bodies can be set by passing body parameters:

const form = new FormData(document.getElementById('login-form'));
fetch('/login', {
  method: 'POST',
  body: form
});

Copy to Clipboard

Both request and response (and by extension the fetch() function), will try to intelligently determine the content type. A request will also automatically set a Content-Type header if none is set in the dictionary.

Feature detection

Fetch API support can be detected by checking for the existence of Headers, Request, Response or fetch() on the Window or Worker scope. For example:

if (window.fetch) {
  // run my fetch request here
} else {
  // do something with XMLHttpRequest?
}

Copy to Clipboard

Specifications

Specification
Fetch Standard # fetch-method

Browser compatibility

Report problems with this compatibility data on GitHub

 desktopmobileserver          
 ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on iOSSamsung InternetDeno
fetch42Toggle history14Toggle history39Toggle historyNoToggle history29Toggle history10.1Toggle history42Toggle history42Toggle history39Toggle history29Toggle history10.3Toggle history4.0Toggle history1.0footnoteToggle history
Support for blob: and data:48Toggle history79Toggle history39Toggle historyNoToggle history35Toggle history10.1Toggle history43Toggle history48Toggle history39Toggle history35Toggle history10.3Toggle history5.0Toggle history1.9Toggle history
referrerPolicy52Toggle history79Toggle history52Toggle historyNoToggle history39Toggle history11.1Toggle history52Toggle history52Toggle history52Toggle history41Toggle historyNoToggle history6.0Toggle historyNoToggle history
signal66Toggle history16Toggle history57Toggle historyNoToggle history53Toggle history11.1Toggle history66Toggle history66Toggle history57Toggle history47Toggle history11.3Toggle history9.0Toggle history1.11Toggle history
Available in workers42Toggle history14Toggle history39Toggle historyNoToggle history29Toggle history10.1Toggle history42Toggle history42Toggle history39Toggle history29Toggle history10.3Toggle history4.0Toggle historyYesToggle history

Legend

 

See also

 

SEE ALSO: https://code.tutsplus.com/tutorials/techniques-for-mastering-curl–net-8470

https://code.tutsplus.com/tutorials/http-headers-for-dummies–net-8039

 

HTTP Headers for Dummies

by Burak GuzelMay 12, 2021

Read Time:21 minsLanguages:EnglishČeštinaDeutschEspañolMagyarBahasa IndonesiaItalianoMelayuPусский

Web DevelopmentHTTPWeb Servers

Whether you're a programmer or not, you have seen it everywhere on the web. Even your first Hello World PHP script sent HTTP headers without you realizing it. In this article, we are going to learn about the basics of HTTP headers and how we can use them in our web applications.

What Are HTTP Headers?

HTTP stands for "Hypertext Transfer Protocol". The entire World Wide Web uses this protocol. It was established in the early 1990s. Almost everything you see in your browser is transmitted to your computer over HTTP. For example, when you opened this article page, your browser probably sent over 40 HTTP requests and received HTTP responses for each.

HTTP headers are the core part of these HTTP requests and responses, and they carry information about the client browser, the requested page, the server, and more.

diagram of HTTP request

Example

When you type a URL in your address bar, your browser sends an HTTP request, and it may look like this:

GET /tutorials/other/top-20-mysql-best-practices/ HTTP/1.1
Host: code.tutsplus.com
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5 (.NET CLR 3.5.30729)
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
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
Cookie: PHPSESSID=r2t5uvjq435r4q7ib3vtdjq120
Pragma: no-cache
Cache-Control: no-cache

The first line is the "Request Line", which contains some basic information on the request. And the rest are the HTTP headers.

After that request, your browser receives an HTTP response that may look like this:

HTTP/1.x 200 OK
Transfer-Encoding: chunked
Date: Sat, 28 Nov 2009 04:36:25 GMT
Server: LiteSpeed
Connection: close
X-Powered-By: W3 Total Cache/0.8
Pragma: public
Expires: Sat, 28 Nov 2009 05:36:25 GMT
Etag: "pub1259380237;gz"
Cache-Control: max-age=3600, public
Content-Type: text/html; charset=UTF-8
Last-Modified: Sat, 28 Nov 2009 03:50:37 GMT
X-Pingback: https://code.tutsplus.com/xmlrpc.php
Content-Encoding: gzip
Vary: Accept-Encoding, Cookie, User-Agent
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Top 20+ MySQL Best Practices - Nettuts+</title>
<!-- ... rest of the html ... -->

The first line is the "Status Line", followed by "HTTP Headers", until the blank line. After that, the "content" starts (in this case, the HTML output).

When you look at the source code of a web page in your browser, you will only see the HTML portion and not the HTTP headers, even though they actually have been transmitted together, as you can see above.

These HTTP requests are also sent and received for other things, such as images, CSS files, JavaScript files, etc. That's why I said earlier that your browser sent at least 40 or more HTTP requests as you loaded just this article page.

Now, let's start reviewing the structure in more detail.

How to See HTTP Headers

I used Firefox Firebug to analyze HTTP headers, but you can use the Developer Tools in Firefox, Chrome, or any modern web browser to view HTTP headers.

In PHP:

  • getallheaders() gets the request headers. You can also use the $_SERVER array.
  • headers_list() gets the response headers.

Further in the article, we will see some code examples in PHP.

HTTP Request Structure

HTTP Request Structure

The first line of the HTTP request is called the request line and consists of three parts:

  • The "method" indicates what kind of request this is. The most common methods are GET, POST, and HEAD.
  • The "path" is generally the part of the URL that comes after the host (domain). For example, when requesting "https://code.tutsplus.com/tutorials/top-20-mysql-best-practices–net-7855" , the path portion is "/tutorials/top-20-mysql-best-practices–net-7855".
  • The protocol part contains HTTP and the version, which is usually 1.1 in modern browsers.

The remainder of the request contains HTTP headers as Name: Value pairs on each line. These contain various information about the HTTP request and your browser. For example, the User-Agent line provides information on the browser version and the Operating System you are using. Accept-Encoding tells the server if your browser can accept compressed output like gzip.

You may have noticed that the cookie data is also transmitted inside an HTTP header. And if there was a referring URL, that would have been in the header too.

Most of these headers are optional. This HTTP request could have been as small as this:

GET /tutorials/other/top-20-mysql-best-practices/ HTTP/1.1``Host: code.tutsplus.com

And you would still get a valid response from the web server.

Request Methods

The three most commonly used request methods are GET, POST, and HEAD. You're probably already familiar with the first two from writing HTML forms.

GET: Retrieve a Document

This is the main method used for retrieving HTML, images, JavaScript, CSS, etc. Most data that loads in your browser was requested using this method.

For example, when loading an Envato Tuts+ article, the very first line of the HTTP request looks like so:

GET /tutorials/other/top-20-mysql-best-practices/ HTTP/1.1``...

Once the HTML loads, the browser will start sending GET requests for images that may look like this:

GET https://mlxzzgdzt2jx.i.optimole.com/cb:yX5x.1db17/w:auto/h:auto/q:mauto/f:best/ig:avif/https://clickety-clack.click/wp-content/themes/tuts_theme/images/header_bg_tall.png HTTP/1.1``...

Web forms can be set to use the GET method. Here's an example.

<form method="GET" action="foo.php">
 
First Name: <input type="text" name="first_name" /> <br />
Last Name: <input type="text" name="last_name" /> <br />
 
<input type="submit" name="action" value="Submit" />
 
</form>

When that form is submitted, the HTTP request begins like this:

GET /foo.php?first_name=John&last_name=Doe&action=Submit HTTP/1.1``...

You can see that each form input was added to the query string.

POST: Send Data to the Server

Even though you can send data to the server using GET and the query string, in many cases POST will be preferable. Sending large amounts of data using GET is not practical and has limitations.

POST requests are most commonly sent by web forms. Let's change the previous form example to a POST method.

<form method="POST" action="foo.php">
 
First Name: <input type="text" name="first_name" /> <br />
Last Name: <input type="text" name="last_name" /> <br />
 
<input type="submit" name="action" value="Submit" />
 
</form>

Submitting that form creates an HTTP request like this:

POST /foo.php HTTP/1.1
Host: localhost
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5 (.NET CLR 3.5.30729)
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
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
Referer: http://localhost/test.php
Content-Type: application/x-www-form-urlencoded
Content-Length: 43
 
first_name=John&last_name=Doe&action=Submit

There are three important things to note here:

  • The path in the first line is simply /foo.php, and there is no query string anymore.
  • Content-Type and Content-Length headers have been added, which provide information about the data being sent.
  • All the data is now sent after the headers, with the same format as the query string.

POST method requests can also be made via AJAX, applications, cURL, etc. And all file upload forms are required to use the POST method.

HEAD: Retrieve Header Information

HEAD is identical to GET, except the server does not return the content in the HTTP response. When you send a HEAD request, it means that you are only interested in the response code and the HTTP headers, not the document itself.

With this method, the browser can check if a document has been modified, for caching purposes. It can also check if the document exists at all.

For example, if you have a lot of links on your website, you can periodically send HEAD requests to all of them to check for broken links. This will work much faster than using GET.

HTTP Response Structure

After the browser sends the HTTP request, the server responds with an HTTP response. Excluding the content, it looks like this:

HTTP Response Structure

The first piece of data is the protocol. This is again usually HTTP/1.x or HTTP/1.1 on modern servers.

The next part is the status code, followed by a short message. Code 200 means that our GET request was successful and the server will return the contents of the requested document, right after the headers.

We've all seen 404 pages. This number actually comes from the status code part of the HTTP response. If a GET request is made for a path that the server cannot find, it will respond with a 404 instead of 200.

The rest of the response contains headers just like the HTTP request. These values can contain information about the server software, when the page/file was last modified, the MIME type, etc…

Again, most of those headers are actually optional.

HTTP Status Codes

  • 200s are used for successful requests.
  • 300s are for redirections.
  • 400s are used if there was a problem with the request.
  • 500s are used if there was a problem with the server.
200 OK

As mentioned before, this status code is sent in response to a successful request.

206 Partial Content

If an application requests only a range of the requested file, the 206 code is returned. It's most commonly used with download managers that can stop and resume a download, or split the download into pieces.

404 Not Found

404 Not Found error

When the requested page or file was not found, a 404 response code is sent by the server.

401 Unauthorized

Password-protected web pages send this code. If you don't enter a login correctly, you may see the following in your browser.

401 Unauthorized response

Note that this only applies to HTTP password-protected pages that pop up login prompts like this:

login prompt

403 Forbidden

If you are not allowed to access a page, this code may be sent to your browser. This often happens when you try to open a URL for a folder that contains no index page. If the server settings do not allow the display of the folder contents, you will get a 403 error.

For example, on my local server I created an images folder. Inside this folder I put an .htaccess file with this line: "Options -Indexes". Now when I try to open http://localhost/images/, I see this:

403 Forbidden HTTP response

There are other ways in which access can be blocked and 403 responses can be sent. For example, you can block by IP address, with the help of some htaccess directives.

order allow,deny``deny from 192.168.44.201``deny from 224.39.163.12``deny from 172.16.7.92``allow from all
302 (or 307) Moved Temporarily & 301 Moved Permanently

These two codes are used for redirecting a browser. For example, when you use a URL shortening service, such as bit.ly, that's exactly how they forward the people who click on their links.

Both 302 and 301 are handled very similarly by the browser, but they can have different meanings to search engine spiders. For instance, if your website is down for maintenance, you may redirect to another location using 302. The search engine spider will continue checking your page later in the future. But if you redirect using 301, it will tell the spider that your website has moved to that location permanently. For example, https://net.tutsplus.com redirects to https://code.tutsplus.com—that is the new canonical URL.

500 Internal Server Error

500 Internal Server Error

This code is usually seen when a web script crashes. Most CGI scripts do not output errors directly to the browser, unlike PHP. If there are any fatal errors, they will just send a 500 status code. And the programmer then needs to search the server error logs to find the error messages.

Complete List

You can find the complete list of HTTP status codes with their explanations on Wikipedia.

HTTP Headers in HTTP Requests

Now, we'll review some of the most common HTTP headers found in HTTP requests.

Almost all of these headers can be found in the $_SERVER array in PHP. You can also use the getallheaders() function to retrieve all headers at once.

Host

An HTTP request is sent to a specific IP address. But since most servers are capable of hosting multiple websites under the same IP, they must know which domain name the browser is looking for.

Host: code.tutsplus.com

This is basically the host name, including the domain and the subdomain.

In PHP, it can be found as $_SERVER['HTTP_HOST'] or $_SERVER['SERVER_NAME'].

User-Agent
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5 (.NET CLR 3.5.30729)

This header can carry several pieces of information, such as:

  • browser name and version
  • operating system name and version
  • default language

This is how websites can collect certain general information about their surfers' systems. For example, they can detect if the surfer is using a cellphone browser and redirect them to a mobile version of their website which works better on smaller screens.

In PHP, it can be found with: $_SERVER['HTTP_USER_AGENT'].

if ( strstr($_SERVER['HTTP_USER_AGENT'],'MSIE 6') ) {
    echo "Please stop using IE6!";
}
Accept-Language
Accept-Language: en-us,en;q=0.5

This header displays the default language setting of the user. If a website has different language versions, it can redirect a new surfer based on this data.

It can carry multiple languages, separated by commas. The first one is the preferred language, and each other listed language can carry a "q" value, which is an estimate of the user's preference for the language (min. 0 max. 1).

In PHP, it can be found as: $_SERVER["HTTP_ACCEPT_LANGUAGE"].

if (substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2) == 'fr') {
    header('Location: http://french.mydomain.com');
}
Accept-Encoding
Accept-Encoding: gzip,deflate

Most modern browsers support gzip and will send this in the header. The web server then can send the HTML output in a compressed format. This can reduce the size by up to 80% to save bandwidth and time.

In PHP, it can be found as: $_SERVER["HTTP_ACCEPT_ENCODING"]. However, when you use the ob_gzhandler() callback function, it will check this value automatically, so you don't need to.

// enables output buffering
// and all output is compressed if the browser supports it
ob_start('ob_gzhandler');
If-Modified-Since

If a web document is already cached in your browser, and you visit it again, your browser can check if the document has been updated by sending this:

If-Modified-Since: Sat, 28 Nov 2009 06:38:19 GMT

If it was not modified since that date, the server will send a "304 Not Modified" response code, and no content—and the browser will load the content from the cache.

In PHP, it can be found as: $_SERVER['HTTP_IF_MODIFIED_SINCE'].

// assume $last_modify_time was the last the output was updated
 
// did the browser send If-Modified-Since header?
if(isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
 
    // if the browser cache matches the modify time
    if ($last_modify_time == strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
 
        // send a 304 header, and no content
        header("HTTP/1.1 304 Not Modified");
        exit;
    }
 
}

There is also an HTTP header named Etag, which can be used to make sure the cache is current. We'll talk about this shortly.

As the name suggests, this sends the cookies stored in your browser for that domain.

Cookie: PHPSESSID=r2t5uvjq435r4q7ib3vtdjq120; foo=bar

These are name=value pairs separated by semicolons. Cookies can also contain the session id.

In PHP, individual cookies can be accessed with the $_COOKIE array. You can directly access the session variables using the $_SESSION array, and if you need the session id, you can use the session_id() function instead of the cookie.

echo $_COOKIE['foo'];
// output: bar
echo $_COOKIE['PHPSESSID'];
// output: r2t5uvjq435r4q7ib3vtdjq120
session_start();
echo session_id();
// output: r2t5uvjq435r4q7ib3vtdjq120
Referer

As the name suggests, this HTTP header contains the referring URL.

For example, if I visit the Envato Tuts+ Code homepage and click on an article link, this header is sent to my browser:

Referer: https://code.tutsplus.com/

In PHP, it can be found as $_SERVER['HTTP_REFERER'].

if (isset($_SERVER['HTTP_REFERER'])) {
 
    $url_info = parse_url($_SERVER['HTTP_REFERER']);
 
    // is the surfer coming from Google?
    if ($url_info['host'] == 'www.google.com') {
 
        parse_str($url_info['query'], $vars);
 
        echo "You searched on Google for this keyword: ". $vars['q'];
 
    }
 
}
// if the referring URL was:
// http://www.google.com/search?source=ig&hl=en&rlz=&=&q=http+headers&aq=f&oq=&aqi=g-p1g9
// the output will be:
// You searched on Google for this keyword: http headers

You may have noticed the word "referrer" is misspelled as "referer". Unfortunately it made into the official HTTP specifications like that and got stuck.

Authorization

When a web page asks for authorization, the browser opens a login window. When you enter a username and password in this window, the browser sends another HTTP request, but this time it contains this header.

Authorization: Basic bXl1c2VyOm15cGFzcw==

The data inside the header is base64 encoded. For example, base64_decode('bXl1c2VyOm15cGFzcw==') would return 'myuser:mypass'.

In PHP, these values can be found as $_SERVER['PHP_AUTH_USER'] and $_SERVER['PHP_AUTH_PW'].

More on this when we talk about the WWW-Authenticate header.

HTTP Headers in HTTP Responses

Now we are going to look at some of the most common HTTP headers found in HTTP responses.

In PHP, you can set response headers using the header() function. PHP already sends certain headers automatically, for loading the content, setting cookies, etc. You can see the headers that are sent, or will be sent, with the headers_list() function. You can check if the headers have been sent already with the headers_sent() function.

Cache-Control

Here's the definition from w3.org:

The Cache-Control general-header field is used to specify directives which MUST be obeyed by all caching mechanisms along the request/response chain.

These "caching mechanisms" include gateways and proxies that your ISP may be using.

For example:

Cache-Control: max-age=3600, public

public means that the response may be cached by anyone. max-age indicates how many seconds the cache is valid for. Allowing your website to be cached can reduce server load and bandwidth, as well as improving load times in the browser.

Caching can also be prevented by using the no-cache directive.

Cache-Control: no-cache

For more detailed info, see w3.org.

Content-Type

This header indicates the "MIME type" of the document. The browser then decides how to interpret the contents based on this. For example, an HTML page (or a PHP script with HTML output) may return this:

Content-Type: text/html; charset=UTF-8

text is the type, and html is the subtype of the document. The header can also contain more information, such as charset.

For a GIF image, this may be sent:

Content-Type: image/gif

The browser can decide to use an external application or browser extension based on the MIME type. For example, this will cause Adobe Reader or the browser's built-in PDF reader to be loaded:

Content-Type: application/pdf

When loading directly, Apache can usually detect the MIME type of a document and send the appropriate header. Also, most browsers have some amount of fault tolerance and auto-detection of the MIME types, in case the headers are wrong or not present.

You can find a list of common MIME types in the MDN Web Docs.

In PHP, you can use the finfo_file() function to detect the MIME type of a file.

Content-Disposition

This header instructs the browser to open a file download box, instead of trying to parse the content. For example:

Content-Disposition: attachment; filename="download.zip"

That will cause the browser to do this:

security warning message

Note that the appropriate Content-Type header should also be sent along with this:

Content-Type: application/zip``Content-Disposition: attachment; filename="download.zip"
Content-Length

When content is going to be transmitted to the browser, the server can indicate its size (in bytes) using this header.

Content-Length: 89123

This is especially useful for file downloads. That's how the browser can determine the progress of the download.

For example, here is a dummy script I wrote, which simulates a large download.

// it's a zip file
header('Content-Type: application/zip');
// 1 million bytes (about 1megabyte)
header('Content-Length: 1000000');
// load a download dialogue, and save it as download.zip
header('Content-Disposition: attachment; filename="download.zip"');
 
// 1000 times 1000 bytes of data
for ($i = 0; $i < 1000; $i++) {
    echo str_repeat(".",1000);
 
    // sleep to slow down the download
    usleep(50000);
}

The result is:

download progress message

Now I am going to comment out the Content-Length header:

// it's a zip file
header('Content-Type: application/zip');
// the browser won't know the size
// header('Content-Length: 1000000');
// load a download dialogue, and save it as download.zip
header('Content-Disposition: attachment; filename="download.zip"');
 
// 1000 times 1000 bytes of data
for ($i = 0; $i < 1000; $i++) {
    echo str_repeat(".",1000);
 
    // sleep to slow down the download
    usleep(50000);
}

Now the result is:

download progress with no total size shown

The browser can only tell you how many bytes have been downloaded, but it does not know the total amount. And the progress bar is not showing the progress.

Etag

This is another header that is used for caching purposes. It looks like this:

Etag: "pub1259380237;gz"

The web server may send this header with every document it serves. The value can be based on the last modify date, the file size, or even the checksum value of a file. The browser then saves this value as it caches the document. The next time the browser requests the same file, it sends this in the HTTP request:

If-None-Match: "pub1259380237;gz"

If the Etag value of the document matches that, the server will send a 304 code instead of 200, and no content. The browser will load the contents from its cache.

Last-Modified

As the name suggests, this header indicates the last modify date of the document, in GMT format:

$modify_time = filemtime($file);
 
header("Last-Modified: " . gmdate("D, d M Y H:i:s", $modify_time) . " GMT");

It offers another way for the browser to cache a document. The browser may send this in the HTTP request:

If-Modified-Since: Sat, 28 Nov 2009 06:38:19 GMT

We already talked about this earlier, in the If-Modified-Since section.

Location

This header is used for redirections. If the response code is 301 or 302, the server must also send this header. For example, when you go to https://net.tutsplus.com, your browser will receive this:

HTTP/1.x 301 Moved Permanently``...``Location: https://code.tutsplus.com/``...

In PHP, you can redirect a surfer like so:

header(``'Location: https://code.tutsplus.com/'``);

By default, that will send a 302 response code. If you want to send a 301 instead:

header(``'Location: https://code.tutsplus.com/'``, true, 301);

When a website wants to set or update a cookie in your browser, it will use this header.

Set-Cookie: skin=noskin; path=/; domain=.amazon.com; expires=Sun, 29-Nov-2009 21:42:28 GMT``Set-Cookie: session-id=120-7333518-8165026; path=/; domain=.amazon.com; expires=Sat Feb 27 08:00:00 2010 GMT

Each cookie is sent as a separate header. Note that cookies set via JavaScript do not go through HTTP headers.

In PHP, you can set cookies using the setcookie() function, and PHP sends the appropriate HTTP headers.

setcookie(``"TestCookie"``, ``"foobar"``);

Which causes this header to be sent:

Set-Cookie: TestCookie=foobar

If the expiration date is not specified, the cookie is deleted when the browser window is closed.

WWW-Authenticate

A website may send this header to authenticate a user through HTTP. When the browser sees this header, it will open up a login dialogue window.

WWW-Authenticate: Basic realm="Restricted Area"

Which looks like this:

authentication required window

There is a section in the PHP manual that has code samples on how to do this in PHP.

if (!isset($_SERVER['PHP_AUTH_USER'])) {
    header('WWW-Authenticate: Basic realm="My Realm"');
    header('HTTP/1.0 401 Unauthorized');
    echo 'Text to send if user hits Cancel button';
    exit;
} else {
    echo "<p>Hello {$_SERVER['PHP_AUTH_USER']}.</p>";
    echo "<p>You entered {$_SERVER['PHP_AUTH_PW']} as your password.</p>";
}
Content-Encoding

This header is usually set when the returned content is compressed.

Content-Encoding: gzip

In PHP, if you use the ob_gzhandler() callback function, it will be set automatically for you.

How to Send HTTP Headers

After reading the tutorial up to this point, you should have a good idea of what HTTP headers are and what their different values mean. Some headers are sent and received automatically when you make a request to a server and get a response back.

However, there will be situations where you want to send your own custom headers besides the ones sent by the client or server.

One of the most common ways of sending your own headers in a request is by using the cURL library in PHP. The library comes with a bunch of functions to handle all your needs. There are four basic steps involved:

  1. You use curl_init() to start your cURL session. You can pass it the URL you want to request.
  2. The curl_setopt() function is used to configure the request according to your needs. This is where you can set your own headers by using the CURLOPT_HTTPHEADER option.
  3. After you have set all the options, you can execute the request by calling curl_exec().
  4. Finally, you can close the session by calling the curl_close() function.

Here is a basic example that sends a request to https://code.tutsplus.com/tutorials.

<?php
 
$ch = curl_init("https://code.tutsplus.com/tutorials");
 
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:88.0) Gecko/20100101 Firefox/88.0",
    "Accept-Language: en-US,en;q=0.5"
));
 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
 
curl_close($ch);
 
echo $output;
?>

You can learn more about cURL by reading these two tutorials. They cover all the basics of the library to help you get started.

  • img

    PHP

    Techniques for Mastering cURL

    Burak Guzel

  • img

    PHP

    How to Use cURL in PHP

    Sajal Soni

If you want to send response headers in PHP, then you should use the header() function. Among other things, one common use is redirecting visitors to other pages. This can be done by using the Location header. Here is an example:

<?php
 
header('Location: https://code.tutsplus.com/tutorials');
 
// Other PHP or HTML code.
?>

You have to remember to call the header() function before any kind of output either in HTML or in PHP. Even blank output is not permitted. Otherwise, you will get the Headers already sent error.

https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers

HTTP headers

HTTP headers let the client and the server pass additional information with an HTTP request or response. An HTTP header consists of its case-insensitive name followed by a colon (:), then by its value. Whitespace before the value is ignored.

Custom proprietary headers have historically been used with an X- prefix, but this convention was deprecated in June 2012 because of the inconveniences it caused when nonstandard fields became standard in RFC 6648; others are listed in an IANA registry, whose original content was defined in RFC 4229. IANA also maintains a registry of proposed new HTTP headers.

Headers can be grouped according to their contexts:

  • Request headers contain more information about the resource to be fetched, or about the client requesting the resource.
  • Response headers hold additional information about the response, like its location or about the server providing it.
  • Representation headers contain information about the body of the resource, like its MIME type, or encoding/compression applied.
  • Payload headers contain representation-independent information about payload data, including content length and the encoding used for transport.

Headers can also be grouped according to how proxies handle them:

  • End-to-end headers

    These headers must be transmitted to the final recipient of the message: the server for a request, or the client for a response. Intermediate proxies must retransmit these headers unmodified and caches must store them.

  • Hop-by-hop headers

    These headers are meaningful only for a single transport-level connection, and must not be retransmitted by proxies or cached. Note that only hop-by-hop headers may be set using the Connection header.

Authentication

  • WWW-Authenticate

    Defines the authentication method that should be used to access a resource.

  • Authorization

    Contains the credentials to authenticate a user-agent with a server.

  • Proxy-Authenticate

    Defines the authentication method that should be used to access a resource behind a proxy server.

  • Proxy-Authorization

    Contains the credentials to authenticate a user agent with a proxy server.

Caching

  • Age

    The time, in seconds, that the object has been in a proxy cache.

  • Cache-Control

    Directives for caching mechanisms in both requests and responses.

  • Clear-Site-Data

    Clears browsing data (e.g. cookies, storage, cache) associated with the requesting website.

  • Expires

    The date/time after which the response is considered stale.

  • Pragma

    Implementation-specific header that may have various effects anywhere along the request-response chain. Used for backwards compatibility with HTTP/1.0 caches where the Cache-Control header is not yet present.

  • Warning Deprecated

    General warning information about possible problems.

Client hints

HTTP Client hints are a set of request headers that provide useful information about the client such as device type and network conditions, and allow servers to optimize what is served for those conditions.

Servers proactively requests the client hint headers they are interested in from the client using Accept-CH. The client may then choose to include the requested headers in subsequent requests.

  • Accept-CH Experimental

    Servers can advertise support for Client Hints using the Accept-CH header field or an equivalent HTML <meta> element with http-equiv attribute.

  • Accept-CH-Lifetime Experimental Deprecated

    Servers can ask the client to remember the set of Client Hints that the server supports for a specified period of time, to enable delivery of Client Hints on subsequent requests to the server's origin.

The different categories of client hints are listed below.

User agent client hints

The UA client hints are request headers that provide information about the user agent and the platform/architecture on which it is running:

Device client hints

  • Content-DPR DeprecatedExperimental

    Response header used to confirm the image device to pixel ratio in requests where the DPR client hint was used to select an image resource.

  • Device-Memory DeprecatedExperimental

    Approximate amount of available client RAM memory. This is part of the Device Memory API.

  • DPR DeprecatedExperimental

    Client device pixel ratio (DPR), which is the number of physical device pixels corresponding to every CSS pixel.

  • Viewport-Width DeprecatedExperimental

    A number that indicates the layout viewport width in CSS pixels. The provided pixel value is a number rounded to the smallest following integer (i.e. ceiling value).

  • Width DeprecatedExperimental

    A number that indicates the desired resource width in physical pixels (i.e. intrinsic size of an image).

Network client hints

Network client hints allow a server to choose what information is sent based on the user choice and network bandwidth and latency.

Conditionals

  • Last-Modified

    The last modification date of the resource, used to compare several versions of the same resource. It is less accurate than ETag, but easier to calculate in some environments. Conditional requests using If-Modified-Since and If-Unmodified-Since use this value to change the behavior of the request.

  • ETag

    A unique string identifying the version of the resource. Conditional requests using If-Match and If-None-Match use this value to change the behavior of the request.

  • If-Match

    Makes the request conditional, and applies the method only if the stored resource matches one of the given ETags.

  • If-None-Match

    Makes the request conditional, and applies the method only if the stored resource doesn't match any of the given ETags. This is used to update caches (for safe requests), or to prevent uploading a new resource when one already exists.

  • If-Modified-Since

    Makes the request conditional, and expects the resource to be transmitted only if it has been modified after the given date. This is used to transmit data only when the cache is out of date.

  • If-Unmodified-Since

    Makes the request conditional, and expects the resource to be transmitted only if it has not been modified after the given date. This ensures the coherence of a new fragment of a specific range with previous ones, or to implement an optimistic concurrency control system when modifying existing documents.

  • Vary

    Determines how to match request headers to decide whether a cached response can be used rather than requesting a fresh one from the origin server.

Connection management

  • Connection

    Controls whether the network connection stays open after the current transaction finishes.

  • Keep-Alive

    Controls how long a persistent connection should stay open.

Content negotiation

Content negotiation headers.

  • Accept

    Informs the server about the types of data that can be sent back.

  • Accept-Encoding

    The encoding algorithm, usually a compression algorithm, that can be used on the resource sent back.

  • Accept-Language

    Informs the server about the human language the server is expected to send back. This is a hint and is not necessarily under the full control of the user: the server should always pay attention not to override an explicit user choice (like selecting a language from a dropdown).

Controls

  • Expect

    Indicates expectations that need to be fulfilled by the server to properly handle the request.

  • Max-Forwards

    TBD

Cookies

CORS

Learn more about CORS here.

Downloads

  • Content-Disposition

    Indicates if the resource transmitted should be displayed inline (default behavior without the header), or if it should be handled like a download and the browser should present a "Save As" dialog.

Message body information

  • Content-Length

    The size of the resource, in decimal number of bytes.

  • Content-Type

    Indicates the media type of the resource.

  • Content-Encoding

    Used to specify the compression algorithm.

  • Content-Language

    Describes the human language(s) intended for the audience, so that it allows a user to differentiate according to the users' own preferred language.

  • Content-Location

    Indicates an alternate location for the returned data.

Proxies

  • Forwarded

    Contains information from the client-facing side of proxy servers that is altered or lost when a proxy is involved in the path of the request.

  • X-Forwarded-For Non-Standard

    Identifies the originating IP addresses of a client connecting to a web server through an HTTP proxy or a load balancer.

  • X-Forwarded-Host Non-Standard

    Identifies the original host requested that a client used to connect to your proxy or load balancer.

  • X-Forwarded-Proto Non-Standard

    Identifies the protocol (HTTP or HTTPS) that a client used to connect to your proxy or load balancer.

  • Via

    Added by proxies, both forward and reverse proxies, and can appear in the request headers and the response headers.

Redirects

  • Location

    Indicates the URL to redirect a page to.

Request context

  • From

    Contains an Internet email address for a human user who controls the requesting user agent.

  • Host

    Specifies the domain name of the server (for virtual hosting), and (optionally) the TCP port number on which the server is listening.

  • Referer

    The address of the previous web page from which a link to the currently requested page was followed.

  • Referrer-Policy

    Governs which referrer information sent in the Referer header should be included with requests made.

  • User-Agent

    Contains a characteristic string that allows the network protocol peers to identify the application type, operating system, software vendor or software version of the requesting software user agent. See also the Firefox user agent string reference.

Response context

  • Allow

    Lists the set of HTTP request methods supported by a resource.

  • Server

    Contains information about the software used by the origin server to handle the request.

Range requests

  • Accept-Ranges

    Indicates if the server supports range requests, and if so in which unit the range can be expressed.

  • Range

    Indicates the part of a document that the server should return.

  • If-Range

    Creates a conditional range request that is only fulfilled if the given etag or date matches the remote resource. Used to prevent downloading two ranges from incompatible version of the resource.

  • Content-Range

    Indicates where in a full body message a partial message belongs.

Security

  • Cross-Origin-Embedder-Policy (COEP)

    Allows a server to declare an embedder policy for a given document.

  • Cross-Origin-Opener-Policy (COOP)

    Prevents other domains from opening/controlling a window.

  • Cross-Origin-Resource-Policy (CORP)

    Prevents other domains from reading the response of the resources to which this header is applied.

  • Content-Security-Policy (CSP)

    Controls resources the user agent is allowed to load for a given page.

  • Content-Security-Policy-Report-Only

    Allows web developers to experiment with policies by monitoring, but not enforcing, their effects. These violation reports consist of JSON documents sent via an HTTP POST request to the specified URI.

  • Expect-CT

    Allows sites to opt in to reporting and/or enforcement of Certificate Transparency requirements, which prevents the use of misissued certificates for that site from going unnoticed. When a site enables the Expect-CT header, they are requesting that Chrome check that any certificate for that site appears in public CT logs.

  • Feature-Policy

    Provides a mechanism to allow and deny the use of browser features in its own frame, and in iframes that it embeds.

  • Origin-Isolation Experimental

    Provides a mechanism to allow web applications to isolate their origins.

  • Strict-Transport-Security (HSTS)

    Force communication using HTTPS instead of HTTP.

  • Upgrade-Insecure-Requests

    Sends a signal to the server expressing the client's preference for an encrypted and authenticated response, and that it can successfully handle the upgrade-insecure-requests directive.

  • X-Content-Type-Options

    Disables MIME sniffing and forces browser to use the type given in Content-Type.

  • X-Download-Options

    The X-Download-Options HTTP header indicates that the browser (Internet Explorer) should not display the option to "Open" a file that has been downloaded from an application, to prevent phishing attacks as the file otherwise would gain access to execute in the context of the application. (Note: related MS Edge bug).

  • X-Frame-Options (XFO)

    Indicates whether a browser should be allowed to render a page in a

  • X-Permitted-Cross-Domain-Policies

    Specifies if a cross-domain policy file (crossdomain.xml) is allowed. The file may define a policy to grant clients, such as Adobe's Flash Player (now obsolete), Adobe Acrobat, Microsoft Silverlight (now obsolete), or Apache Flex, permission to handle data across domains that would otherwise be restricted due to the Same-Origin Policy. See the Cross-domain Policy File Specification for more information.

  • X-Powered-By

    May be set by hosting environments or other frameworks and contains information about them while not providing any usefulness to the application or its visitors. Unset this header to avoid exposing potential vulnerabilities.

  • X-XSS-Protection

    Enables cross-site scripting filtering.

HTTP Public Key Pinning (HPKP)

HTTP Public Key Pinning has been deprecated and removed in favor of Certificate Transparency and Expect-CT.

  • Public-Key-Pins

    Associates a specific cryptographic public key with a certain web server to decrease the risk of MITM attacks with forged certificates.

  • Public-Key-Pins-Report-Only

    Sends reports to the report-uri specified in the header and does still allow clients to connect to the server even if the pinning is violated.

Fetch metadata request headers

Fetch metadata request headers provides information about the context from which the request originated. This allows a server to make decisions about whether a request should be allowed based on where the request came from and how the resource will be used.

  • Sec-Fetch-Site

    It is a request header that indicates the relationship between a request initiator's origin and its target's origin. It is a Structured Header whose value is a token with possible values cross-site, same-origin, same-site, and none.

  • Sec-Fetch-Mode

    It is a request header that indicates the request's mode to a server. It is a Structured Header whose value is a token with possible values cors, navigate, no-cors, same-origin, and websocket.

  • Sec-Fetch-User

    It is a request header that indicates whether or not a navigation request was triggered by user activation. It is a Structured Header whose value is a boolean so possible values are ?0 for false and ?1 for true.

  • Sec-Fetch-Dest

    It is a request header that indicates the request's destination to a server. It is a Structured Header whose value is a token with possible values audio, audioworklet, document, embed, empty, font, image, manifest, object, paintworklet, report, script, serviceworker, sharedworker, style, track, video, worker, and xslt.

  • Service-Worker-Navigation-Preload

    A request header sent in preemptive request to fetch() a resource during service worker boot. The value, which is set with NavigationPreloadManager.setHeaderValue(), can be used to inform a server that a different resource should be returned than in a normal fetch() operation.

Server-sent events

  • Last-Event-ID

    TBD

  • NEL Experimental

    Defines a mechanism that enables developers to declare a network error reporting policy.

  • Ping-From

    TBD

  • Ping-To

    TBD

  • Report-To

    Used to specify a server endpoint for the browser to send warning and error reports to.

Transfer coding

  • Transfer-Encoding

    Specifies the form of encoding used to safely transfer the resource to the user.

  • TE

    Specifies the transfer encodings the user agent is willing to accept.

  • Trailer

    Allows the sender to include additional fields at the end of chunked message.

WebSockets

Other

  • Accept-Push-Policy Experimental

    A client can express the desired push policy for a request by sending an Accept-Push-Policy header field in the request.

  • Accept-Signature Experimental

    A client can send the Accept-Signature header field to indicate intention to take advantage of any available signatures and to indicate what kinds of signatures it supports.

  • Alt-Svc

    Used to list alternate ways to reach this service.

  • Date

    Contains the date and time at which the message was originated.

  • Early-Data Experimental

    Indicates that the request has been conveyed in TLS early data.

  • Large-Allocation Deprecated

    Tells the browser that the page being loaded is going to want to perform a large allocation.

  • Link

    The Link entity-header field provides a means for serializing one or more links in HTTP headers. It is semantically equivalent to the HTML `` element.

  • Push-Policy Experimental

    A Push-Policy defines the server behavior regarding push when processing a request.

  • Retry-After

    Indicates how long the user agent should wait before making a follow-up request.

  • Signature Experimental

    The Signature header field conveys a list of signatures for an exchange, each one accompanied by information about how to determine the authority of and refresh that signature.

  • Signed-Headers Experimental

    The Signed-Headers header field identifies an ordered list of response header fields to include in a signature.

  • Server-Timing

    Communicates one or more metrics and descriptions for the given request-response cycle.

  • Service-Worker-Allowed

    Used to remove the path restriction by including this header in the response of the Service Worker script.

  • SourceMap

    Links generated code to a source map.

  • Upgrade

    The relevant RFC document for the Upgrade header field is RFC 7230, section 6.7. The standard establishes rules for upgrading or changing to a different protocol on the current client, server, transport protocol connection. For example, this header standard allows a client to change from HTTP 1.1 to HTTP 2.0, assuming the server decides to acknowledge and implement the Upgrade header field. Neither party is required to accept the terms specified in the Upgrade header field. It can be used in both client and server headers. If the Upgrade header field is specified, then the sender MUST also send the Connection header field with the upgrade option specified. For details on the Connection header field please see section 6.1 of the aforementioned RFC.

  • X-DNS-Prefetch-Control

    Controls DNS prefetching, a feature by which browsers proactively perform domain name resolution on both links that the user may choose to follow as well as URLs for items referenced by the document, including images, CSS, JavaScript, and so forth.

  • X-Firefox-Spdy Deprecated Non-Standard

    TBD

  • X-Pingback Non-Standard

    TBD

  • X-Requested-With

    TBD

  • X-Robots-TagNon-Standard

    The X-Robots-Tag HTTP header is used to indicate how a web page is to be indexed within public search engine results. The header is effectively equivalent to <meta name="robots" content="...">.

  • X-UA-Compatible Non-Standard

    Used by Internet Explorer to signal which document mode to use.

Contributing

You can help by writing new entries or improving the existing ones.

See also

Scroll to Top