Campos de cabeçalho HTTP são componentes da seção de cabeçalho das mensagens de requisição e resposta no Protocolo de Transferência de Hipertexto (HTTP). Eles definem os parâmetros de operação de uma transação HTTP.
Formato geral Os campos de cabeçalho são transmitidos depois da linha de requisição ou resposta, a qual é a primeira linha de uma mensagem. Campos de cabeçalho são pares de nome-valor separados por dois pontos em formato de cadeia de caracteres de texto simples, terminados por uma sequência de caracteres de retorno de carro (carriage return - CR) e de avanço de linha (line feed - LF). O final da secção de cabeçalho é indicado por um campo vazio, resultando na transmissão de dois pares CR-LF consecutivos. Historicamente, linhas longas podem ser dobradas em várias linhas. Linhas de continuação são indicadas pela presença de um espaço (space - SP) ou uma tabulação horizontal (horizontal tab - HT) com o primeiro caractere na linha seguinte. Esta quebra hoje é considerada obsoleta.
Nomes de campos Um conjunto principal de campos é padronizado pela Internet Engineering Task Force (IETF) no [RFC 7231]. Um registo oficial destes domínios, bem como os de especificações suplementares é mantido pela IANA. Nomes de campos adicionais e os valores admissíveis podem ser definidos por cada aplicação.
O registro permanente de campos de cabeçalho e o repositório de registos provisórios são mantidos pela IANA.
Campos de cabeçalho não padrões foram convencionalmente marcados pela prefixação do nome do campo com X-. No entanto, esta convenção tornou-se obsoleta em junho de 2012, devido aos inconvenientes que causou quando os campos não padrões tornaram-se padrões.
A restrição anterior sobre a utilização de Downgraded- também já foi levantada.
Valores de campos
Alguns campos podem conter comentários (ou seja, nos campos User-Agent, Server, Via), que podem ser ignorados pelo software.
Muitos valores de campo podem conter um par chave-valor qualidade (q), especificando um peso para usar na negociação de conteúdo.
Limites de tamanho A norma não impõe limites ao tamanho de cada nome de campo de cabeçalho ou valor, ou para o número de campos. No entanto, a maioria dos servidores, clientes e softwares de proxy impõem alguns limites por razões práticas e de segurança. Por exemplo, o servidor Apache 2.3, por padrão, limita o tamanho de cada campo para 8190 bytes, e pode existir no máximo 100 campos de cabeçalho em uma única solicitação.
Campos de resposta Nome do campo Descrição Exemplo EstadoAccess-Control-Allow-Origin Especifica quais sites podem participar de compartilhamento de recursos de origem cruzada Access-Control-Allow-Origin: * Provisório Accept-Ranges Quais tipos de arranjo de conteúdo parcial este servidor suporta Accept-Ranges: bytes Permanente Age A idade que o objeto possui em um cache de proxy em segundos Age: 12 Permanente Allow Ações válidas para um recurso especificado. Para ser utilizado por um 405 Método não permitido Allow: GET, HEAD Permanente Cache-Control Diz todos os mecanismos de cache do servidor para o cliente se eles podem armazenar em cache esse objeto. É medido em segundosCache-Control: max-age=3600 Permanente Connection Opções desejadas para a conexão. Connection: close Permanente Content-Encoding O tipo de codificação usada nos dados. HTTP compression. Content-Encoding: gzip Permanente Content-Language A linguagem em que o conteúdo está Content-Language: da Permanente Content-Length O comprimento do corpo da resposta em octetos (8-bit bytes)Content-Length: 348 Permanente Content-Location Um local alternativo para os dados retornados Content-Location: /index.htm Permanente Content-MD5 A Base64-encoded binary MD5 sum of the content of the response Content-MD5: Q2hlY2sgSW50ZWdyaXR5IQ== Permanente Content-Disposition An opportunity to raise a "File Download" dialogue box for a known MIME type with binary format or suggest a filename for dynamic content. Quotes are necessary with special characters. Content-Disposition: attachment; filename="fname.ext" Permanente Content-Range Where in a full body message this partial message belongs Content-Range: bytes 21010-47021/47022 Permanente Content-Type O tipo MIME deste conteúdo Content-Type: text/html; charset=utf-8 Permanente Date A data e horário de envio da mensagem (no formato "HTTP-date" como definido pelo RFC 7231) Date: Tue, 15 Nov 1994 08:12:31 GMT Permanente ETag An identifier for a specific version of a resource, often a message digest ETag: "737060cd8c284d8af7ad3082f209582d" Permanente Expires Gives the date/time after which the response is considered stale Expires: Thu, 01 Dec 1994 16:00:00 GMT Permanente: padrão Last-Modified The last modified date for the requested object (in "HTTP-date" format as defined by RFC 7231) Last-Modified: Tue, 15 Nov 1994 12:45:26 GMT Permanente Link Used to express a typed relationship with another resource, where the relation type is defined by RFC 5988 Link: </feed>; rel="alternate"Indicate the canonical version of a URL by responding with the Link rel="canonical" HTTP header Retrieved: 2012-02-09 Permanente Location Used in redirection, or when a new resource has been created. Localização: http://www.w3.org/pub/WWW/People.html Permanente P3P This field is supposed to set P3P policy, in the form of P3P:CP="your_compact_policy". However, P3P did not take off,W3C P3P Work Suspended most browsers have never fully implemented it, a lot of websites set this field with fake policy text, that was enough to fool browsers the existence of P3P policy and grant permissions for third party cookies. P3P: CP="This is not a P3P policy! See http://www.google.com/support/accounts/bin/answer.py?hl=en&answer=151657 for more info." Permanente Pragma Implementation-specific fields that may have various effects anywhere along the request-response chain. Pragma: no-cache Permanente Proxy-Authenticate Request authentication to access the proxy. Proxy-Authenticate: Basic Permanente Refresh Used in redirection, or when a new resource has been created. This refresh redirects after 5 seconds. Refresh: 5; url=http://www.w3.org/pub/WWW/People.html Proprietary and non-standard: a header extension introduced by Netscape and supported by most web browsers. Retry-After If an entity is temporarily unavailable, this instructs the client to try again later. Value could be a specified period of time (in seconds) or a HTTP-date. Example 1: Retry-After: 120 Example 2: Retry-After: Fri, 07 Nov 2014 23:59:59 GMTPermanente Server A name for the server Server: Apache/2.4.1 (Unix) Permanente Set-Cookie An HTTP cookie Set-Cookie: UserID=JohnDoe; Max-Age=3600; Version=1 Permanente: standard Status CGI header field specifying the status of the HTTP response. Normal HTTP responses use a separate "Status-Line" instead, defined by RFC 7230. Status: 200 OK Not listed as a registered field name Strict-Transport-Security A HSTS Policy informing the HTTP client how long to cache the HTTPS only policy and whether this applies to subdomains. Strict-Transport-Security: max-age=16070400; includeSubDomains Permanente: padrão Trailer The Trailer general field value indicates that the given set of header fields is present in the trailer of a message encoded with chunked transfer coding. Trailer: Max-Forwards Permanente Transfer-Encoding The form of encoding used to safely transfer the entity to the user. Currently defined methods are: chunked, compress, deflate, gzip, identity. Transfer-Encoding: chunked Permanente Upgrade Ask the client to upgrade to another protocol. Upgrade: HTTP/2.0, SHTTP/1.3, IRC/6.9, RTA/x11 Permanente Vary Tells downstream proxies how to match future request headers to decide whether the cached response can be used rather than requesting a fresh one from the origin server. Vary: * Permanente Via Informs the client of proxies through which the response was sent. Via: 1.0 fred, 1.1 example.com (Apache/1.1) Permanente Warning A general warning about possible problems with the entity body. Warning: 199 Miscellaneous warning Permanente WWW-Authenticate Indicates the authentication scheme that should be used to access the requested entity. WWW-Authenticate: Basic Permanente X-Frame-Options Clickjacking protection: deny - no rendering within a frame, sameorigin - no rendering if origin mismatch, allow-from - allow from specified location, allowall - non-standard, allow from any location X-Frame-Options: deny Obsolete
Campos de resposta não padrões comuns
Field name Description Example Public-Key-Pins Man-in-the-middle attack mitigation, announces hash of website's authentic TLS certificate Public-Key-Pins: max-age=2592000; pin-sha256="E9CZ9INDbd+2eRQozYqqbQ2yXLVKB9+xcprMF+44U1g="; X-XSS-Protection Cross-site scripting (XSS) filter X-XSS-Protection: 1; mode=blockContent-Security-Policy, X-Content-Security-Policy, X-WebKit-CSPContent Security Policy definition.X-WebKit-CSP: default-src 'self' X-Content-Type-Options The only defined value, "nosniff", prevents Internet Explorer from MIME-sniffing a response away from the declared content-type. This also applies to Google Chrome, when downloading extensions. X-Content-Type-Options: nosniff X-Powered-By specifies the technology (e.g. ASP.NET, PHP, JBoss) supporting the web application (version details are often in X-Runtime, X-Version, or X-AspNet-Version) X-Powered-By: PHP/5.4.0 X-UA-Compatible Recommends the preferred rendering engine (often a backward-compatibility mode) to use to display the content. Also used to activate Chrome Frame in Internet Explorer. X-UA-Compatible: IE=EmulateIE7X-UA-Compatible: IE=edgeX-UA-Compatible: Chrome=1
Categoria:HTTP campos de cabeçalho HTTP