--- title: HTTP slug: Web/HTTP tags: - HTTP - Headers - NeedsTranslation - TopicStub - Web - Web Development translation_of: Web/HTTP ---

{{ HTTPSidebar }}                                                                                                     

L'Hypertext Transfer Protocol (HTTP) è un protocollo del livello di applicazione per il trasferimento di ipertesti. È usato per le comunicazioni tra i web browser e i web server, sebbene in linea di principio possa essere utilizzato anche per altri scopi. Segue un classico modello client-server, con apertura di una conessione da parte del client, creazione di una richiesta e poi attesa della risposta da parte del server dopo aver ricevuto la richiesta. È anche un protocollo senza stato, cioè il server non mantiene nessun tipo di dato (stato) delle richieste.

Sebbene spesso basato su un livello TCP/IP, può essere usato su qualsiasi livello di trasporto orientato alle connessioni.

Documentazione

HTTP Header
I messaggi Header HTTP vengono utilizzati per descrivere con precisione la risorsa da recuperare o il comportamento del server o del client. Header con proprietà personalizzate possono essere aggiunti usando il prefisso 'X-'; altri sono elencati in un registro IANA, il cui contenuto originale è stato definito in RFC 4229. IANA mantiene anche un registro delle nuove proposte di messaggi Header HTTP.
HTTP cookie
Come lavorano i cookie è stato definito nel RFC 6265. Quando riceve una richiesta HTTP, un server può inviare un header Set-Cookie con la risposta. Successivamente, il valore del cookie viene inviato insieme a ogni richiesta effettuata sullo stesso server sotto forma di un'intestazione HTTP Cookie. Inoltre, è possibile specificare un ritardo di scadenza. È possibile specificare anche restrizioni a un dominio e un percorso specifici.
Autenticazione di accesso di base
Nel contesto di una transazione HTTP, l'autenticazione di accesso di base è un metodo per un HTTP user agent per fornire un nome utente e una password quando si effettua una richiesta.
Pipelining HTTP FAQ
Pipelining HTTP/1.1 FAQ
Controllo accessi HTTP (CORS)
Le richieste HTTP cross-site sono richieste HTTP per risorse da un dominio diverso rispetto al dominio della risorsa che effettua la richiesta.  Ad esempio, una risorsa caricata dal Dominio A (http://domaina.example) come una pagina Web HTML, effettua una richiesta per una risorsa sul Dominio B (http://domainb.foo), come un'immagine, usando l'elemento img (http://domainb.foo/image.jpg). Questo si verifica molto comunemente sul Web oggi: le pagine caricano un numero di risorse in modo cross-site, inclusi fogli di stile CSS, immagini e script e altre risorse.
Controllo del prefetching DNS
Firefox 3.5 esegue il prefetching DNS. Questa è una funzionalità con cui Firefox esegue proattivamente la risoluzione dei nomi di dominio su entrambi i link che l'utente può scegliere di seguire e gli URL per gli elementi a cui fa riferimento il documento, incluse immagini, CSS, JavaScript e così via. Questo prefetch viene eseguito in background, in modo che il DNS sia già stato risolto nel momento in cui gli elementi di riferimento sono effettivamente necessari. Ciò riduce la latenza quando, ad esempio, l'utente fa effettivamente clic su un collegamento.
Codici di risposta HTTP
I codici di risposta HTTP indicano se una specifica richiesta HTTP è stata completata con successo. Le risposte sono raggruppate in cinque classi: risposte informative, risposte positive, reindirizzamenti, errori del client e errori del server.

A brief history of HTTP

Since its original conception, as a protocol with one single method (GET) and returning only HTML pages, the HTTP protocol went through several revisions. The first documented version was HTTP/0.9 in 1991, corresponding to the original version. Very simple, it has a rudimentary search capability via the HTML {{ HTMLElement("isindex") }} element and an extension of the URL using the '?' character.

Then, in 1992, a version was published that became, with some minor changes, HTTP/1.0 (finalized in RFC 1945 in May 1996). One major improvement over the previous version was the ability to transmit files of different types, like images, videos, scripts, CSS documents, and so on, instead of only HTML files: this is achieved by using MIME types in conjunction with the Content-Type: header.

In 1995, the IETF  began developing a new version of HTTP, which would become HTTP/1.1. It quickly spread into wide usage, and it was officially standardized in 1997 in RFC 2068, with minor fixes in RFC 2616 two years later.

HTTP/1.1 brought the ability to reuse established connections for subsequent requests, greatly improving the performance of the protocol by lowering the latency between them; this is especially useful with complex HTML documents that need to fetch several subsequent files, like images or style sheets. It also brought the Host: header, which allows a single server, listening on a specific port, to receive requests for several websites; this paved the way for colocating numerous websites on one single server, greatly reducing the cost of hosting.

Since then, the HTTP protocol evolved by adding new headers, defining new behaviors without the need to fundamentally change the protocol. Unknown headers are simply ignored by servers or clients.

HTTP/1.1 is currently being revised by the IETF HTTPbis Working Group.

HTTP request methods

The request method indicates the action to be performed by the server. The HTTP/1.1 standard defines seven methods and allows other methods to be added later. Over the years, a few ones have been added in standards like WebDAV. The  IETF HTTPbis Working Group is currently working on an IANA registry to list them all. If a server receives a request method that it doesn't know, it must return a 501 Not implemented response; if it knows the method but is configured not to answer it, it must return a 405 Method not allowed response. Two methods are required to be supported: HEAD and GET; all others are optional.

Two specific semantics are defined in the standard and are crucial for web developers: the safety property and the idempotent property.

Safe methods

A safe method is a method that doesn't have any side-effects on the server. In other words, this property means that the method must be used only for retrieval of data. The safe HTTP methods defined in HTTP/1.1 are:

Notes:

Idempotent methods

An idempotent method is a method such that the side-effects on the server of several identical requests with the method are the same as the side-effects of one single request.

Other methods

Many more methods, such as PROPFIND or PATCH are defined in other standards-track RFCs of the IETF, like WebDAV.

The CONNECT method is defined in RFC 2817.

HTTP Requests Methods in HTML Forms

In HTML, different HTTP request methods can be specified in the {{ htmlattrxref("method", "form") }} attribute of the {{ HTMLElement("form") }} element, but also to the {{ htmlattrxref("formmethod", "input") }} of the {{ HTMLElement("input") }} and {{ HTMLElement("button") }} elements. But not all HTTP methods can be used with these attributes; only GET and POST method are allowed by the HTML specification. See this StackExchange answer why other HTTP request methods are not allowed by the HTML specification.

Note: The choice of a GET or POST method for HTML forms is not neutral. Because the GET method is a safe method, it should be used only in cases where no side-effect is expected; e.g., it shouldn't be used to transmit an order, as this order is a side-effect. In all cases where such side-effects are expected, the POST method should be used.

HTTP response codes

When answering a client request, the server sends back a three-digit number indicating whether the request was successfully processed. These codes can be grouped in five categories:

A web developer shouldn't encounter many other response codes, but people building requests using the XMLHTTPRequest function may hit less usual response codes.

More on redirection responses

Starting in Gecko 9.0 {{ geckoRelease("9.0") }}, redirections (such as 301 and 307) that specify a javascript: URI are no longer performed. Instead, a bad connection error is presented. This helps avoid cross-site scripting attacks. See {{ bug(255119) }} if you want more details.

HTTP headers

HTTP headers allow the client and the server to pass additional information with the request or the response. A request header consists of its case-insensitive name followed by a colon ':', then by its value (without CRLF in it). Leading white space before the value is ignored.

Headers are grouped according the context in which they may appear:

General headers
These headers apply to both requests and responses but are unrelated to the data eventually transmitted in the body. They therefore apply only to the message being transmitted. There are only a few of them and new ones cannot be added without increasing the version number of the HTTP protocol. The exhaustive list for HTTP/1.1 is {{ httpheader("Cache-Control") }}, {{ httpheader("Connection") }}, {{ httpheader("Date") }}, {{ httpheader("Pragma") }}, {{ httpheader("Trailer") }}, {{ httpheader("Transfer-Encoding") }}, {{ httpheader("Upgrade") }}, {{ httpheader("Via") }} and {{ httpheader("Warning") }}.
Request headers
These headers give more precise information about the resource to be fetched or about the client itself. Among them one can find cache-related headers, transforming a GET method in a conditional GET, like {{ httpheader("If-Modified-Since") }}, user-preference information like {{ httpheader("Accept-Language") }} or {{ httpheader("Accept-Charset") }} or plain client information like {{ httpheader("User-Agent") }}. New request headers cannot officially be added without increasing the version number of the HTTP protocol. But, it is common for new request headers to be added if both the server and the client agree on their meaning. In that case, a client should not assume that they will be handled adequately by the server; unknown request headers are handled as entity headers.
Response headers
These headers give more information about the resource sent back, like its real location ({{ httpheader("Location") }}) or about the server itself, like its name and version ({{ httpheader("Server") }}). New response headers cannot be added without increasing the version number of the HTTP protocol. But, it is common for new response headers to be added if both the server and the client agree on their meaning. In that case, a server should not assume that they will be handled adequately by the client ; unknown response headers are handled as entity headers.
Entity headers
These headers give more information about the body of the entity, like its length ({{ httpheader("Content-Length") }}), an identifying hash ({{ httpheader("Content-MD5") }}), or its MIME-type ({{ httpheader("Content-Type") }}). New entity headers can be added without increasing the version number of the HTTP protocol.

Headers can also be grouped according to how caching and non-caching proxies handle them:

End-to-end headers
These headers must be transmitted to the final recipient of the message; that is, the server for a request message or the client for a response message. Such a header means that intermediate proxies must retransmit it unmodified and also that caches must store it.
Hop-by-hop headers
These headers are meaningful only for a single transport-level connection and must not be retransmitted by proxies or cached. Such headers are: {{ httpheader("Connection") }}, {{ httpheader("Keep-Alive") }}, {{ httpheader("Proxy-Authenticate") }}, {{ httpheader("Proxy-Authorization") }}, {{ httpheader("TE") }}, {{ httpheader("Trailers") }}, {{ httpheader("Transfer-Encoding") }} and {{ httpheader("Upgrade") }}. Note that only hop-by-hop headers may be set using the {{ httpheader("Connection") }} general header.

In order to learn about the specific semantic of each header, see its entry in the comprehensive list of HTTP headers.

Useful request headers

Among the numerous HTTP request headers, several are especially useful when set correctly. If you are building your own requests, by using XMLHTTPRequest or when writing an extension and sending custom HTTP requests via XPCOM, then it is important to ensure the presence of headers that are often set by browsers based on the preferences of the user.

Controlling the language of the resource
Most user-agents, like Firefox, allow the user to set a preference for the language for receiving a resource. The browser translate this into an {{ httpheader("Accept-Language") }} header. It is good practice for web developers, when building specific HTTP requests, to include such a header too.
Using conditional GET
Caching is a major tool to accelerate the display of web pages. Even when parts of a webpage are refreshed via an XMLHTTPRequest:, it is a good idea to use the {{ httpheader("If-Modified-Since") }} header (and other similar ones) in order to fetch the new content only if it has changed. This approach lowers the burden on the network.

Useful response headers

The configuration of a web server is a critical part to ensure good performance and optimal security of a web site. Among the numerous HTTP response headers, several are of specific importance and should be configured on the server

Restricting framing

Several cross-site scripting (XSS) attacks take advantage of the ability to put third-party content inside an {{ HTMLElement("frame") }} or {{ HTMLElement("iframe") }}. In order to mitigate that risk, modern browsers have introduced the CSP frame-ancestors directive. By setting it with the value 'none', it prevents the browser from displaying this resource inside of a frame. Using it on critical resources (like those containing a formularies or critical information) will reduce the risk caused by XSS attacks. Note that this specific HTTP response header is not the only way to mitigate XSS risks; other techniques, like setting some Content Security Policies, may be helpful too.

Compression

Minimizing the amount of data transferred accelerates the display of a web page. Though most techniques, like CSS Sprites, should be applied on the site itself, compression of data must be set at the web server level. If set, resources requested by the client with an {{ httpheader("Accept-Encoding") }} request header are compressed using the appropriate method and sent back with a {{ httpheader("Content-Encoding") }} response header. Setting these in Apache 2 servers is done by using the mod_deflate module.

Note: Be aware that not all data formats can be efficiently compressed. Already-compressed media data, like JPEG images or most audio and video formats, do not shrink using another pass of compression. In fact, they often become larger due to the overhead of the compression method. It is important not to try to compress these resource types any further; there is no advantage in size and the compression/decompression mechanism is resource-intensive.

Controlling cache

HTTP Caching is a technique that prevents the same resource from being fetched several times if it hasn't change. Configuring the server with the correct response headers allows the user-agent to adequately cache the data. In order to do that, be sure that:

Setting the correct MIME types

The MIME type is the mechanism to tell the client the kind of document transmitted: the extension of a file name has no meaning on the web. It is therefore important that the server is correctly set up so that the correct MIME type is transmitted with each document: user-agents often use this MIME-type to determine what default action to do when a resource is fetched.

Note:

See also

{{ languages( { "ja": "ja/HTTP"} ) }}