Please note, this is a STATIC archive of website developer.mozilla.org from 03 Nov 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

Revision 946919 of HTTP

  • URL ревизии: Web/HTTP
  • Заголовок ревизии: HTTP
  • ID ревизии: 946919
  • Создано:
  • Автор: lerniri
  • Это текущая ревизия? Нет
  • Комментарий
Метки: 

Содержание ревизии

{{ HTTPSidebar }}

Протокол передачи гипер текста ( Hypertext Transfer Protocol - HTTP) это прикладной протокол для передачи данных. Он используется для общения между веб браузерами и веб серверами, хотя в принципе HTTP может использоваться и для других целей. Протокол следует классической клиент-серверной модели, когда клиент открывает соединение, инициирует запрос, а затем ждет ответа. HTTP не поддерживает статусы взаимодействия клиента и сервера ( stateless protocol )

Не смотря на то, что HTTP основан на TCP/IP , он так же может использовать любой транспорт

 

Документация

HTTP заголовки / HTTP headers 
Заголовки HTTP сообщения используются для точного описания загружаемого ресурса  или поведения сервера или клиента. Пользовательские заголовки можно добавить используя 'X-' префикс; другие перечислены в  IANA registry, содержание которого в свою очередь определено в RFC 4229. IANA так же поддерживает регистр предложенных новых HTTP заголовков .
HTTP куки / HTTP cookies
Как работают куки можно почитать в RFC 6265. В момент получения HTTP запроса , сервер может послать Set-Cookie заголовок в ответе. После этого, значение куки посылается с каждым запросом к этому серверу. Делается это в форме Cookie HTTP header. В дополнение, можно указать истечение срока куки, а так же ограничения для специфического домена или пути.
 Базовая аутентификация / Basic access authentication
В контексте HTTP транзакции, базовая аутентификация это метод, используемый HTTP юзер агентом (User Agent) для предоставления имени и пароля пользователя при инициации запроса.
HTTP pipelining FAQ
HTTP/1.1 Pipelining FAQ
Контроль доступа (совместное использование ресурсов между разными источниками)  / HTTP access control (CORS)
Кросс-сайт HTTP запросы это запросы к ресурсам, находящимся домене отличающимся от того, с которого производится запрос.  Напрмер, ресурс загружаемый с домена А (https://domaina.example) - HTML веб страница, запрашивает ресурс с домена Б (https://domainb.foo) - изображение, используя img тег (https://domainb.foo/image.jpg).  Это происходит сплошь и рядом в мире веба - страницы загружают различные ресурсы в кросс-сайт манере, включая стили (CSS) , изображения  и скрипты и другие ресурсы. 
Контроль предварительной загрузки DNS / Controlling DNS prefetching 
Firefox 3.5 выполняет предварительную загрузку DNS / DNS prefetching. При помощи данной функции Firefox заранее получает доменное имя ссылки, по которой следует пользователь, а также резолвит URL'ы для объектов ссылки на которые указаны в документе, включая изображения, CSS, JavaScript и так далее. Эта предварительная загрузка выполняется в фоновом режиме, так что вполне вероятно, что к моменту обращения к объектам в документе, DNS уже получен. Это уменьшает задержки, когда , например пользователь кликает на ссылку.
Коды ответа / HTTP response codes
Коды ответа  HTTP  указывают на результат выполнения определенного HTTP запроса. Ответы сгруппированы в пять категорий: информационные ответы, удачные ответы, перенаправления, ошибки клиента, и ошибки сервера.

View All...

 

Краткая история HTTP

С момента своего первого появления в качестве протокола с одним единственным методом (GET) , возвращаемого только HTML страницы, HTTP прошел через несколько ревизий. Первая версия, документированная как HTTP/0.9 in 1991 считается первоначальной.  Очень простой, у него был рудимент в виде поискового функционала через HTML {{ HTMLElement("isindex") }} элемент и расширение URL при помощи символа  '?'.

Затем в 1992 была опубликована версия, которая с минимальными изменениями стала  HTTP/1.0 (финализирована в RFC 1945 в Мае 1996). Одно важное улучшение по сравнению с предыдущей версией заключалось в возможности передавать файлы разных типов, а не только HTML : Изображения, видео, скрипты, CSS документы. Это было достигнуто использованием MIME типов  вместе с заголовком Content-Type.

В 1995, IETF  начала разработку новой версии HTTP, которая должна была стать HTTP/1.1. Она очень быстро стала широко использоваться, и была официально стандартизирована в 1997 в RFC 2068, с небольшими исправлениями в RFC 2616 2 года спустя.

HTTP/1.1 превнесла возможность повторно использовать установленное подключение для последовательных запросов, что значительно улучшило производительность протокола, уменьшив уровень задержек между запросами. Это особенно полезно в случаях сложных HTML документов, которым необходимо получить несколько последовательных файлов, таких как изображения или стили. Также в новой версии появился Host: заголовок, который позволяет одному серверу на один порт, получать запросы для нескольких веб сайтов; эта возможность проложила путь к размещению нескольких веб сайтов на одном сервере, что значительно уменьшило затраты на хостинг.

С тех пор HTTP протокол развивался добавлением новых  заголовков, определяющих новые поведения без необходимости фундаментального изменения протокола. Неизвестные заголовки просто игнорируются серверами и клиентами. 

В настоящее время HTTP/1.1 пересматривается рабочей группой IETF HTTPbis Working Group.

HTTP сессия

Так как HTTP это клиент-серверный протокол , HTTP сессия состоит из трёх фаз:

  1. Клиент устанавливает TCP соеденения (или другое соединение, если не используется TCP транспорт).
  2. Клиент отправляет запрос и ждёт ответа. 
  3. Сервер обрабатывает запрос и посылает ответ, в котором содержится код статуса и соответствующие данные. 

Начиная с версии HTTP/1.1, после третьей фазы соединение не закрывается, так как клиенту позволяется инициировать другой запрос. То есть, вторая и третья фазы могут повторяться.

Установка соединения

Так как HTTP это клиент-серверный протокол, соединение всегда устанавливается клиентом. Открыть соединение в HTTP это значит установить соединение через соответствующий транспорт, обычно TCP.

В случае с TCP, в качестве порта HTTP сервера по умолчанию на компьютере используется порт 80, хотя другие также часто используются, например 8000 or 8080. URL загружаемой страницы содержит доменное имя и порт, который можно и не  указывать если он соответствует порту по умолчанию. 

Имеем в виду: Клиент-серверная модель не позволяет серверу посылать данные клиенту без явного запроса этих данных. Чтобы обойти эту проблему, веб разработчики используют различные техники: периодически пингуют сервер используя XMLHTTPRequest Javascript объект, HTML WebSockets API, или похожие протоколы.

Отправка запроса клиента

Когда соединение установлено user-agent может послать запрос. (user-agent это обычно веб браузер, но может им не быть) Клиентский запрос это текстовые директивы, разделенные между собой при помощи CRLF (переноса строки).  Сам запрос включает в себя три блока:

  1. Первые строки содержат метод запроса и его параметры: 
    • путь к документу - абсолютная URL без указания протокола и доменного имени
    • версию HTTP протокола 
  2. Каждая последующая строка представляет собой HTTP заголовок и передает серверу некоторую информацию о типах предпочитаемых данных (наприм. какой язык , какие MIME типы) или инструкции меняющие поведение сервера (наприм. не отправлять ответ, если он уже в кэше) . Эти HTTP заголовки формируют блок, который заканчивается пустой строкой.
  3. Последний блок является не обязательным и содержит дополнительные данные. По большей части используется методом POST.

Примеры запросов

  • Получаем главную страницу developer.mozilla.org,  https://developer.mozilla.org/, и говорим серверу, что user-agent предпочитает страницу на французском, если это возможно:
    GET / HTTP/1.1
    Host: developer.mozilla.org
    Accept-Language: fr 
    
    

    Обращаем внимание на пустую строку в конце, которая отделяет блок данных от блока заголовков. Так как в запросе отсутствует Content-Length: HTTP заголовок, блок с данными пуст и сервер может начать обработку запроса, как только получит пустую строку, означающую конец заголовков.

  • Отправляем результат сабмита формы:
    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
    

Структура ответа от сервера

После того как присоединенный агент отправил свой запрос, веб сервер обрабатывает его и отправляет ответ. По аналогии с клиентским запросом, ответ сервера это текстовые директивы разделенные между собой CRLF, сгруппированные в три разных блока:

  1. Первая строка - строка статуса, состоит из подтверждения используемой HTTP версии и статуса запроса (и его значения в виде понятным человеку).
  2. Последующие строки представляют собой HTTP заголовки, дающие клиенту некоторую информацию о посылаемой дате (прим. тип, размер, алгоритм сжатия, подсказки по кэшированию). Так же как и в случае клиентского запроса, эти HTTP заголовки формируют блок, заканчивающийся пустой строкой.
  3. Последний блок содержит данные (если таковые имеются).

Примеры ответов

  • Успешное получение веб страницы:
    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)
    
    
  • Сообщение о том, что запрашиваемый ресурс был перемещен:
    HTTP/1.1 301 Moved Permanently
    Server: Apache/2.2.3 (Red Hat)
    Content-Type: text/html; charset=iso-8859-1
    Date: Sat, 09 Oct 2010 14:30:24 GMT
    Location: https://developer.mozilla.org/ (this is the new link to the resource; it is expected that the user-agent will fetch it)
    Keep-Alive: timeout=15, max=98
    Accept-Ranges: bytes
    Via: Moz-Cache-zlb05
    Connection: Keep-Alive
    X-Cache-Info: caching
    X-Cache-Info: caching
    Content-Length: 325 (the content contains a default page to display if the user-agent is not able to follow the link)
    
    <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
    <html><head>
    <title>301 Moved Permanently</title>
    </head><body>
    <h1>Moved Permanently</h1>
    <p>The document has moved <a href="https://developer.mozilla.org/">here</a>.</p>
    <hr>
    <address>Apache/2.2.3 (Red Hat) Server at developer.mozilla.org Port 80</address>
    </body></html>
     
    
  • Сообщение о том, что запрашиваемый ресурс не существует:
    HTTP/1.1 404 Not Found
    Date: Sat, 09 Oct 2010 14:33:02 GMT
    Server: Apache
    Last-Modified: Tue, 01 May 2007 14:24:39 GMT
    ETag: "499fd34e-29ec-42f695ca96761;48fe7523cfcc1"
    Accept-Ranges: bytes
    Content-Length: 10732
    Content-Type: text/html
    
    <!DOCTYPE html... (contains a site-customized page helping the user to find the missing resource)
    
    

Постоянные соединения

Постоянные соединения появились в HTTP/1.1 версии. Они позволяют передавать несколько запросов по одному и тому же TCP соединению (или по любому другому транспорту, в случае если не используется TCP/IP). У этой функции есть несколько преимуществ:

  • Благодаря тому, что соединение может быть использовано повторно, запросы можно объединить в один ( HTTP pipelining ), что при отправке поможет уменьшенить задержки.
  • Уменьшение открытия и закрытия TCP соединений, сохраняет время CPU.
  • Перегруженность сети снижается за счет уменьшение общего количества TCP пакетов (меньше открывающих и закрывающих TCP пакетов).
  • У TCP стека появляется больше времени на диагностику перегруженности сети и соответствующие изменения окон отправки и получения данных. 
  • HTTP становится более адаптивным: цена проверки новой функции значительно уменьшается, так как получение ошибки от сервера не ведет к закрытию соединения. 

Методы HTTP запроса

Методы запроса обозначают действие, которое должно быть произведено на сервере. Стандарт HTTP/1.1 определяет семь методов, а также позволяет добавлять другие методы. За последние годы несколько методов было добавлено , например WebDAV. Группа IETF HTTPbis Working Group в настоящее время работает тем, чтобы перечислить все методы в IANA регистре. Если сервер получает метод, который он не знает, он должен вернуть  ответ 501 Not implemented ; Если он знает метод, но сконфигурен не отвечать на него, то сервер должен вернуть 405 Method not allowed ответ. От сервера требуется поддержка двух методов: HEAD and GET; Все остальные не обязательны. 

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:

  • GET, used to retrieve information identified by the request URI. This information may be generated on the fly or the GET may be conditional if any of the {{ httpheader("If-Modified-Since") }}, {{ httpheader("If-Unmodified-Since") }}, {{ httpheader("If-Match") }}, {{ httpheader("If-None-Match") }} or {{ httpheader("If-Range") }} HTTP headers are set. In that latter case the information is only sent back if all the conditions are fulfilled.
  • HEAD, which is identical to GET but without the message body sent.
Notes:
  • Any safe method is also idempotent.
  • Not having any side-effects means, for the GET method, that it must not be used to trigger an action outside the server, like an order in an e-commerce site. If a side-effect is wanted, a non-idempotent method should be used, like POST.
  • When a page is generated on the fly by a script, the script engine may calculate the page as if it was requested by a GET and then strip the data block. This does not cause problem as long as the GET as implemented in the script is safe, but if it has any side-effects (like triggering an order on an e-commerce site), the HEAD method will trigger it too. It is up to the web developer to ensure that both the GET and HEAD method are safely implemented.

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.

  • HEAD and GET, like any safe method, are also idempotent, as a safe method doesn't have side-effects on the server.
  • PUT is the way to upload a new resource on the server. If the resource already exists and is different, it is replaced; if it doesn't exist, it is created.
  • DELETE removes a resource from the server.

Other methods

  • POST is the way to trigger an action on the server. It has side-effects and can be used to trigger an order, to modify a database, to post a message in a forum, and so on.
  • OPTIONS is a request for communication options available on the chain between the client and the server (through eventual proxies); this method is typically sent before any preflighted cross-origin request, in order to know whether it is safe to do it.
    Note: Preflighted cross-origin requests cannot be done on servers which don't allow or support the OPTIONS method.
  • TRACE is a kind of ping between the client and the server (through eventual proxies).

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.

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:

  • Informational responses (of the form 1xx) are provisional responses. Most of the time neither the end user, nor the web developer or webmaster should have to bother with these. The most common is the 100 Continue response, indicating that the client should continue to send its request.
    Note: No information response codes were defined in the HTTP/1.0, and therefore they must not be sent back when this version of the protocol is used.
  • Success responses (of the form 2xx) are for successfully processed requests. The 200 OK response is by far the most common of these responses, but the 206 Partial Content is also often seen when fetching a file or some media data like video or audio.
  • Redirection responses (of the form 3xx) indicate that the resource that the client requested has moved and the server is not able to serve it directly. Most of these responses contain some location information telling where to find the requested resource; user-agents often then retrieve it without further user interaction. The most common responses of this type are 301 Moved Permanently, indicating that the URI given is no longer valid and has been moved to another place, and 302 Found which indicates that the resource has been temporarily moved to another place.
    Note: For webmasters, it is recommended to set up a 301 Moved Permanently redirection when moving pages to another URI, during a site reorganization for example. That allows users following links to still reach the resource and it also teaches search engines and other services the new location of the resource, so that they can transfer their metadata to it. It is also important to add adequate cache headers to the 301 Moved Permanently response so that this information is cached by the client and prevents it from making unnecessary requests to the original URI prior to fetching the resource itself.
  • Client error responses (of the form 4xx) indicate that the request sent by the client is either invalid, incomplete, or doesn't have enough rights to be performed. The most common such response is 404 Not Found which is sent back when the URI requested doesn't exist, but a few others are often presented to the end user, like 400 Bad Request sent when the request isn't a valid HTTP request (as this shouldn't happen but may indicate a bug into the user agent or, less likely, the server) or 403 Forbidden, sent when the client request a resource that does exist but isn't allowed to be transmitted (like a directory content).
  • Server error responses (of the form 5xx) indicate that the server had a problem handling the valid client request. The two most common such responses are 500 Internal Server Error, a generic error code indicating a bug in the server or 503 Service Unavailable indicating that the server cannot process the request due to a temporary problem, like a disabled service for maintenance purposes or the non-availability of a database.

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 been 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 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 X-Frame-Options: response header. By setting it with the value DENY, 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:

  • Any static resource provides an {{ httpheader("Expires") }} response header that is set to far in the future. That way, the resource may stay in the cache until the user-agent flushes it for its own reasons (like reaching its cache size limit).
    Note: On Apache, use the ExpiresDefault directive in your .htaccess to define a relative expires: ExpiresDefault "access plus 1 month".
  • Any dynamic resource provides a {{ httpheader("Cache-control") }} response header. Theoretically, any HTTP request done through a safe method (GET or HEAD) or even through a solely idempotent one (DELETE, PUT) may be cached; but in practice careful study is needed to determine if the caching of the response may lead to inappropriate side-effects.

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:
  • On Apache, one can match file extensions with a given MIME type in the .htaccess using the AddType type directive like AddType image/jpeg jpg.
  • Most web servers send unknown-type resources using the default application/octet-stream MIME type; for security reasons, most browsers, like Firefox, do not allow setting a custom default action for such resources and force the user to store it to disk in order to use it. Some common cases of often incorrectly configured servers happens for the following file types:
    • Rar-encoded files. The ideal would be to be able to set the real type of the encoded files; this often is not possible (as it may not be known to the server and these files may contains several resource of different types). In that case, configure the server to send the application/x-rar-compressed MIME type or some users won't be able to define a useful default action for them.

    • Audio and video files. Only resources with the proper MIME Type will be recognized and played, using a {{ HTMLElement("video") }} or {{ HTMLElement("audio") }} elements. Be sure to use the correct MIME type for audio and video resources.

    • Proprietary file types. Pay special attention when serving a proprietary file type. Be sure not to forget to add an x-prefixed type for it; otherwise, special handling won't be possible. This is especially true with resources using the Keyhole Markup Language, which should be served as application/vnd.google-earth.kml+xml for an optimal user experience.

Community

  • View Mozilla forums... {{ DiscussionList("dev-web-development", "mozilla.dev.web.development") }}

Tools

View All...

See also

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

Источник ревизии

<p>{{ HTTPSidebar }}</p>

<p>Протокол передачи гипер текста (&nbsp;<dfn>Hypertext Transfer Protocol -&nbsp;HTTP)</dfn>&nbsp;это прикладной протокол для передачи данных. Он используется для общения между веб браузерами и веб серверами, хотя в принципе HTTP может использоваться и для других целей. Протокол следует классической клиент-серверной модели, когда клиент открывает соединение, инициирует запрос, а затем ждет ответа. HTTP не поддерживает статусы взаимодействия клиента и сервера (&nbsp;<a href="https://en.wikipedia.org/wiki/Stateless_protocol" title="https://en.wikipedia.org/wiki/Stateless_protocol">stateless protocol</a>&nbsp;)</p>

<p>Не смотря на то, что HTTP основан на TCP/IP , он так же может использовать любой <a href="https://en.wikipedia.org/wiki/Transport_Layer">транспорт</a>.&nbsp;</p>

<p>&nbsp;</p>

<div class="topicpage-table"><!-- div class="section" -->
<h2 class="Documentation" id="Documentation" name="Documentation">Документация</h2>

<dl>
 <dt><a href="/en-US/docs/HTTP/Headers" title="/en-US/docs/HTTP/Headers">HTTP заголовки&nbsp;</a>/ HTTP&nbsp;headers&nbsp;</dt>
 <dd>Заголовки HTTP сообщения используются для точного описания загружаемого ресурса&nbsp;&nbsp;или поведения сервера или клиента. Пользовательские заголовки можно добавить используя&nbsp;'X-' префикс; другие перечислены в &nbsp;<a class="external" href="https://www.iana.org/assignments/message-headers/perm-headers.html" title="https://www.iana.org/assignments/message-headers/perm-headers.html">IANA registry</a>, содержание которого в свою очередь определено в&nbsp;<a class="external" href="https://tools.ietf.org/html/rfc4229" title="https://tools.ietf.org/html/rfc4229">RFC 4229</a>. IANA так же поддерживает&nbsp;<a class="external" href="https://www.iana.org/assignments/message-headers/prov-headers.html" title="https://www.iana.org/assignments/message-headers/prov-headers.html">регистр предложенных новых HTTP заголовков&nbsp;</a>.</dd>
 <dt><a href="/en/Web_Development/HTTP_cookies" title="HTTP cookies">HTTP куки&nbsp;</a>/ HTTP cookies</dt>
 <dd>Как работают куки можно почитать в <a class="external" href="https://tools.ietf.org/html/rfc6265">RFC 6265</a>. В момент получения HTTP запроса , сервер может послать Set-Cookie заголовок в ответе. После этого, значение куки посылается с каждым запросом к этому серверу. Делается это в форме Cookie HTTP header. В дополнение, можно указать истечение срока куки, а так же ограничения для специфического домена или пути.</dd>
 <dt>&nbsp;<a href="/en-US/docs/HTTP/Basic_access_authentication">Базовая аутентификация</a>&nbsp;/ Basic access authentication</dt>
 <dd>В контексте HTTP транзакции, <strong>базовая аутентификация&nbsp;</strong>это метод, используемый&nbsp;<a href="https://developer.mozilla.org/en-US/docs/Web/API/window.navigator.userAgent" title="HTTP user agent">HTTP юзер&nbsp;агентом&nbsp;(User Agent)</a><a href="en-US/docs/Web/API/window.navigator.userAgent">&nbsp;</a>для предоставления имени и пароля пользователя при инициации запроса.</dd>
 <dt><a href="/en/HTTP_Pipelining_FAQ" title="https://developer.mozilla.org/en/HTTP_Pipelining_FAQ">HTTP pipelining FAQ</a></dt>
 <dd>HTTP/1.1 Pipelining FAQ</dd>
 <dt><a href="/en-US/docs/HTTP/Access_control_CORS">Контроль доступа (совместное использование ресурсов между разными источниками) &nbsp;/&nbsp;HTTP access control (CORS)</a></dt>
 <dd><strong>Кросс-сайт HTTP запросы</strong>&nbsp;это запросы к ресурсам, находящимся домене отличающимся от того, с которого производится запрос. &nbsp;Напрмер, ресурс загружаемый с домена А (<code><span class="nowiki">https://domaina.example</span></code>) - HTML веб страница, запрашивает ресурс&nbsp;с домена Б (<span class="nowiki">https://domainb.foo</span>) -&nbsp;изображение, используя <code>img</code> тег (<code><span class="nowiki">https://domainb.foo/image.jpg</span></code>). &nbsp;Это происходит сплошь и рядом в мире веба&nbsp;- страницы загружают различные ресурсы в кросс-сайт манере, включая стили (CSS) , изображения &nbsp;и скрипты и другие ресурсы.&nbsp;</dd>
 <dt><a href="https://developer.mozilla.org/En/Controlling_DNS_prefetching">Контроль&nbsp;предварительной&nbsp;загрузки DNS&nbsp;/</a>&nbsp;<a href="/En/Controlling_DNS_prefetching" title="En/Controlling DNS prefetching">Controlling DNS&nbsp;prefetching</a>&nbsp;</dt>
 <dd>Firefox 3.5 выполняет <strong>предварительную загрузку DNS /</strong>&nbsp;<strong>DNS&nbsp;prefetching</strong>. При помощи данной функции Firefox заранее получает доменное имя&nbsp;ссылки, по которой следует пользователь, а также резолвит URL'ы для объектов ссылки на которые указаны в документе, включая изображения, CSS, JavaScript и так далее. Эта предварительная загрузка выполняется в фоновом режиме, так что вполне вероятно, что к моменту обращения к объектам в документе, DNS уже получен. Это уменьшает задержки, когда , например пользователь кликает на ссылку.</dd>
 <dt><a href="/en-US/docs/HTTP/HTTP_response_codes">Коды ответа&nbsp;/&nbsp;HTTP response codes</a></dt>
 <dd>Коды ответа &nbsp;HTTP&nbsp;&nbsp;указывают на результат выполнения определенного&nbsp;<a href="https://developer.mozilla.org/en/HTTP" title="en/HTTP">HTTP</a> запроса. Ответы сгруппированы в пять категорий: информационные ответы, удачные ответы, перенаправления, ошибки клиента, и ошибки сервера.</dd>
</dl>

<p><span class="alllinks"><a href="/en-US/docs/tag/HTTP" title="tag/HTTP">View All...</a></span></p>
<!--/div-->

<p>&nbsp;</p>
</div>

<h2 id="Краткая_история_HTTP">Краткая история HTTP</h2>

<p>С момента своего первого появления&nbsp;в качестве протокола с одним единственным методом (GET) , возвращаемого только&nbsp;HTML страницы, HTTP прошел через несколько ревизий. Первая версия, документированная как&nbsp;HTTP/0.9 in 1991 считается первоначальной.&nbsp;&nbsp;Очень простой, у него был рудимент в виде поискового функционала через&nbsp;HTML&nbsp;{{ HTMLElement("isindex") }} элемент и расширение&nbsp;URL при помощи символа&nbsp;&nbsp;'<span style="font-family:courier new">?</span>'.</p>

<p>Затем в 1992 была опубликована версия, которая с минимальными изменениями стала&nbsp;&nbsp;HTTP/1.0 (финализирована&nbsp;в <a class="external" href="https://tools.ietf.org/html/rfc1945" title="https://tools.ietf.org/html/rfc1945">RFC 1945</a> в Мае 1996). Одно важное улучшение по сравнению с предыдущей версией заключалось в возможности передавать файлы разных типов, а не только HTML : Изображения, видео, скрипты, CSS документы. Это было достигнуто использованием&nbsp;<a class="external" href="https://en.wikipedia.org/wiki/Mime_types" title="https://en.wikipedia.org/wiki/Mime_types">MIME типов&nbsp;</a>&nbsp;вместе с заголовком&nbsp;<code>Content-Type</code>.</p>

<p>В 1995, <a class="external" href="https://www.ietf.org/" title="https://www.ietf.org/">IETF</a>&nbsp; начала разработку новой версии HTTP, которая должна была стать HTTP/1.1. Она очень быстро стала широко использоваться, и была официально стандартизирована в 1997 в&nbsp;<a class="external" href="https://tools.ietf.org/html/rfc2068" title="https://tools.ietf.org/html/rfc2068">RFC 2068</a>, с небольшими исправлениями в&nbsp;<a class="external" href="https://tools.ietf.org/html/rfc2616" title="https://tools.ietf.org/html/rfc2616">RFC 2616</a> 2 года спустя.</p>

<p>HTTP/1.1 превнесла возможность повторно использовать установленное подключение для последовательных запросов, что значительно улучшило производительность протокола, уменьшив уровень задержек между запросами. Это особенно полезно в случаях сложных&nbsp;HTML документов, которым необходимо получить несколько последовательных файлов, таких как изображения или стили. Также в новой версии появился&nbsp;<code>Host:</code> заголовок, который позволяет одному серверу на один порт, получать запросы для нескольких веб сайтов; эта возможность проложила путь к размещению нескольких веб сайтов на одном сервере, что значительно уменьшило затраты на хостинг.</p>

<p>С тех пор HTTP протокол развивался добавлением новых &nbsp;<a href="/en/HTTP/Headers" title="en/HTTP/Headers">заголовков</a>, определяющих новые поведения без необходимости фундаментального изменения протокола. Неизвестные заголовки просто игнорируются серверами и клиентами.&nbsp;</p>

<p>В настоящее время HTTP/1.1 пересматривается рабочей группой&nbsp;<a class="external" href="https://tools.ietf.org/wg/httpbis/" title="https://tools.ietf.org/wg/httpbis/">IETF&nbsp;HTTPbis&nbsp;Working Group</a>.</p>

<h2 id="HTTP_сессия">HTTP сессия</h2>

<p>Так как&nbsp;HTTP это клиент-серверный протокол , HTTP сессия состоит из трёх фаз:</p>

<ol>
 <li>Клиент устанавливает&nbsp;TCP соеденения (или другое соединение, если не используется&nbsp;TCP транспорт).</li>
 <li>Клиент отправляет запрос и ждёт ответа.&nbsp;</li>
 <li>Сервер обрабатывает запрос и посылает ответ, в котором содержится код статуса и соответствующие данные.&nbsp;</li>
</ol>

<p>Начиная с версии HTTP/1.1, после третьей фазы соединение не закрывается, так как клиенту позволяется инициировать другой запрос. То есть, вторая и третья фазы могут повторяться.</p>

<h3 id="Установка_соединения">Установка соединения</h3>

<p>Так как HTTP это клиент-серверный протокол, соединение всегда устанавливается клиентом. Открыть соединение в&nbsp;HTTP это значит установить соединение через соответствующий транспорт, обычно&nbsp;TCP.</p>

<p>В случае с TCP, в качестве порта HTTP сервера по умолчанию&nbsp;на компьютере используется порт 80, хотя другие также часто используются, например 8000 or 8080. URL загружаемой страницы содержит доменное имя и порт, который можно и не&nbsp;&nbsp;указывать если он соответствует порту по умолчанию.&nbsp;</p>

<div class="note"><strong>Имеем в виду:</strong>&nbsp;Клиент-серверная модель не позволяет серверу посылать данные клиенту без явного запроса этих данных. Чтобы обойти эту проблему, веб разработчики используют различные техники: периодически пингуют сервер используя&nbsp;<a href="/en/DOM/XMLHttpRequest" title="en/XMLHTTPRequest">XMLHTTPRequest</a> Javascript объект, HTML <a href="/en/WebSockets" title="en/WebSockets">WebSockets API</a>, или похожие протоколы.</div>

<h3 id="Отправка_запроса_клиента">Отправка запроса клиента</h3>

<p>Когда соединение установлено user-agent может послать запрос. (user-agent это обычно веб браузер, но может им не быть) Клиентский запрос это текстовые директивы, разделенные между собой при помощи&nbsp;CRLF (переноса строки).&nbsp;&nbsp;Сам запрос включает в себя три блока:</p>

<ol>
 <li>Первые строки&nbsp;содержат&nbsp;метод запроса и его параметры:&nbsp;
  <ul>
   <li>путь к документу - абсолютная&nbsp;URL без указания протокола и доменного имени</li>
   <li>версию HTTP протокола&nbsp;</li>
  </ul>
 </li>
 <li>Каждая последующая строка представляет собой&nbsp;HTTP&nbsp;заголовок и передает серверу некоторую информацию о типах предпочитаемых данных (наприм. какой язык , какие&nbsp;MIME типы) или инструкции меняющие&nbsp;поведение сервера (наприм. не отправлять ответ, если он уже в кэше) . Эти&nbsp;HTTP заголовки формируют блок, который заканчивается пустой строкой.</li>
 <li>Последний блок является не обязательным и содержит дополнительные данные. По большей части используется методом&nbsp;POST.</li>
</ol>

<h4 id="Примеры_запросов">Примеры запросов</h4>

<ul>
 <li>Получаем главную страницу developer.mozilla.org, &nbsp;<a class="linkification-ext external" href="/" title="Linkification: https://developer.mozilla.org/">https://developer.mozilla.org/</a>, и говорим серверу, что user-agent предпочитает страницу на французском, если это возможно:

  <pre>
GET / HTTP/1.1
Host: developer.mozilla.org
Accept-Language: fr 

</pre>

  <p>Обращаем внимание на пустую строку в конце, которая отделяет блок данных от блока заголовков. Так как в запросе отсутствует&nbsp;<code>Content-Length:</code> HTTP&nbsp;заголовок, блок с данными пуст и сервер может начать обработку запроса, как только получит пустую строку, означающую конец заголовков.</p>
 </li>
 <li>Отправляем результат сабмита формы:
  <pre>
POST /contact_form.php HTTP/1.1
Host: developer.mozilla.org
Content-Length: 64
Content-Type: application/x-www-form-urlencoded

name=Joe%20User&amp;request=Send%20me%20one%20of%20your%20catalogue
</pre>
 </li>
</ul>

<h3 id="Структура_ответа_от_сервера">Структура ответа от сервера</h3>

<p>После того как присоединенный агент отправил свой запрос, веб сервер обрабатывает его и отправляет ответ. По аналогии с клиентским запросом, ответ сервера это текстовые директивы разделенные между собой&nbsp;CRLF, сгруппированные в три разных блока:</p>

<ol>
 <li>Первая строка - строка статуса, состоит из подтверждения используемой&nbsp;HTTP версии и статуса запроса (и его значения в виде понятным человеку).</li>
 <li>Последующие строки представляют собой&nbsp;HTTP&nbsp;заголовки, дающие клиенту некоторую информацию о посылаемой дате (прим. тип, размер, алгоритм сжатия, подсказки по кэшированию).&nbsp;Так же как и в случае клиентского запроса, эти&nbsp;HTTP заголовки формируют блок, заканчивающийся пустой строкой.</li>
 <li>Последний блок содержит данные (если таковые имеются).</li>
</ol>

<h4 id="Примеры_ответов">Примеры ответов</h4>

<ul>
 <li>Успешное получение&nbsp;веб страницы:
  <pre>
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

&lt;!DOCTYPE html... <em><strong>(here comes the 29769 bytes of the requested web page)</strong></em>

</pre>
 </li>
 <li>Сообщение о том, что запрашиваемый ресурс был перемещен:
  <pre>
HTTP/1.1 301 Moved Permanently
Server: Apache/2.2.3 (Red Hat)
Content-Type: text/html; charset=iso-8859-1
Date: Sat, 09 Oct 2010 14:30:24 GMT
Location: <a class="linkification-ext" href="../../../../" title="Linkification: https://developer.mozilla.org/">https://developer.mozilla.org/</a> <strong><em>(this is the</em><em> new link to the resource; it is expected that the user-agent will fetch it)</em></strong>
Keep-Alive: timeout=15, max=98
Accept-Ranges: bytes
Via: Moz-Cache-zlb05
Connection: Keep-Alive
X-Cache-Info: caching
X-Cache-Info: caching
Content-Length: 325 <em>(<strong>the content contains a default page to display if the user-agent is not able to follow the link)</strong></em>

&lt;!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"&gt;
&lt;html&gt;&lt;head&gt;
&lt;title&gt;301 Moved Permanently&lt;/title&gt;
&lt;/head&gt;&lt;body&gt;
&lt;h1&gt;Moved Permanently&lt;/h1&gt;
&lt;p&gt;The document has moved &lt;a href="<a class="linkification-ext" href="../../../../" title="Linkification: https://developer.mozilla.org/">https://developer.mozilla.org/</a>"&gt;here&lt;/a&gt;.&lt;/p&gt;
&lt;hr&gt;
&lt;address&gt;Apache/2.2.3 (Red Hat) Server at developer.mozilla.org Port 80&lt;/address&gt;
&lt;/body&gt;&lt;/html&gt;
 
</pre>
 </li>
 <li>Сообщение о том, что запрашиваемый ресурс не существует:
  <pre>
HTTP/1.1 404 Not Found
Date: Sat, 09 Oct 2010 14:33:02 GMT
Server: Apache
Last-Modified: Tue, 01 May 2007 14:24:39 GMT
ETag: "499fd34e-29ec-42f695ca96761;48fe7523cfcc1"
Accept-Ranges: bytes
Content-Length: 10732
Content-Type: text/html

&lt;!DOCTYPE html... <strong><em>(contains a site-customized page helping the user to find the missing resource)</em></strong>

</pre>
 </li>
</ul>

<h3 id="Постоянные_соединения">Постоянные соединения</h3>

<p>Постоянные соединения появились в HTTP/1.1 версии. Они позволяют передавать несколько запросов по одному и тому же&nbsp;TCP соединению&nbsp;(или по любому другому транспорту, в случае если&nbsp;не используется TCP/IP). У этой функции есть несколько преимуществ:</p>

<ul>
 <li>Благодаря тому, что соединение может быть использовано повторно, запросы можно объединить в один ( <a href="/en/HTTP_Pipelining_FAQ">HTTP&nbsp;pipelining</a>&nbsp;), что при отправке поможет&nbsp;уменьшенить&nbsp;задержки.</li>
 <li>Уменьшение открытия и закрытия TCP соединений, сохраняет время&nbsp;CPU.</li>
 <li>Перегруженность сети снижается за счет уменьшение общего количества&nbsp;TCP&nbsp;пакетов (меньше открывающих и закрывающих TCP&nbsp;пакетов).</li>
 <li>У TCP стека появляется больше времени на диагностику перегруженности сети и соответствующие&nbsp;изменения&nbsp;окон отправки и получения данных.&nbsp;</li>
 <li>HTTP&nbsp;становится более адаптивным: цена проверки новой функции значительно уменьшается, так как получение ошибки от сервера не ведет к закрытию соединения.&nbsp;</li>
</ul>

<h2 id="HTTP_request_methods">Методы&nbsp;HTTP запроса</h2>

<p>Методы запроса обозначают действие, которое должно быть произведено на сервере. Стандарт HTTP/1.1 определяет&nbsp;семь методов, а также позволяет добавлять другие методы. За последние годы несколько методов было добавлено , например&nbsp;<a href="/en/WebDAV" title="en/WebDAV">WebDAV</a>. Группа&nbsp;<a class="external" href="https://tools.ietf.org/wg/httpbis/" rel="external nofollow" target="_blank" title="https://tools.ietf.org/wg/httpbis/">IETF&nbsp;HTTPbis&nbsp;Working Group</a>&nbsp;в настоящее время работает тем, чтобы перечислить все методы в&nbsp;IANA регистре. Если сервер получает метод, который он не знает, он должен вернуть&nbsp;&nbsp;ответ&nbsp;<span style="font-family:courier new"><a href="/en/HTTP/HTTP_response_codes#501" rel="internal" title="en/HTTP/HTTP response codes#501">501 Not implemented</a></span>&nbsp;; Если он знает метод, но сконфигурен не отвечать на него, то сервер должен вернуть&nbsp;<span style="font-family:courier new"><a href="/en/HTTP/HTTP_response_codes#501" rel="internal" title="en/HTTP/HTTP response codes#501">405 Method not allowed</a></span> ответ. От сервера требуется поддержка двух методов: HEAD&nbsp;and GET; Все остальные не обязательны.&nbsp;</p>

<p>Two specific semantics are defined in the standard and are crucial for web developers: the <em>safety</em> property and the <em>idempotent</em> property.</p>

<h3 id="Safe_methods">Safe methods</h3>

<p>A <dfn>safe method</dfn> 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 <em>retrieval</em> of data. The safe HTTP methods defined in HTTP/1.1 are:</p>

<ul>
 <li>GET, used to retrieve information identified by the request URI. This information may be generated on the fly or the GET may be conditional if any of the {{ httpheader("If-Modified-Since") }}, {{ httpheader("If-Unmodified-Since") }}, {{ httpheader("If-Match") }}, {{ httpheader("If-None-Match") }} or {{ httpheader("If-Range") }} HTTP&nbsp;headers are set. In that latter case the information is only sent back if all the conditions are fulfilled.</li>
 <li>HEAD, which is identical to GET but without the message body sent.</li>
</ul>

<div class="note"><strong>Notes: </strong>

<ul>
 <li>Any safe method is also <em>idempotent</em>.</li>
 <li>Not having any side-effects means, for the GET method, that it&nbsp;<strong>must</strong> not be used to trigger an action outside the server, like an order in an e-commerce site. If a side-effect is wanted, a non-<em>idempotent</em> method should be used, like POST.</li>
 <li>When a page is generated on the fly by a script, the script engine may calculate the page as if it was requested by a GET and then strip the data block. This does not cause problem as long as the GET as implemented in the script is <em>safe</em>, but if it has any side-effects (like triggering an order on an e-commerce site), the HEAD method will trigger it too. It is up to the web developer to ensure that both the GET and HEAD method are safely implemented.</li>
</ul>
</div>

<h3 id="Idempotent_methods">Idempotent methods</h3>

<p>An <dfn>idempotent method</dfn> 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.</p>

<ul>
 <li>HEAD and GET, like any safe method, are also idempotent, as a safe method doesn't have side-effects on the server.</li>
 <li>PUT is the way to upload a new resource on the server. If the resource already exists and is different, it is replaced; if it doesn't exist, it is created.</li>
 <li>DELETE removes a resource from the server.</li>
</ul>

<h3 id="Other_methods">Other methods</h3>

<ul>
 <li>POST is the way to trigger an action on the server. It has side-effects and can be used to trigger an order, to modify a database, to post a message in a forum, and so on.</li>
 <li>OPTIONS is a request for communication options available on the chain between the client and the server (through eventual proxies); this method is typically sent before any <a href="/En/HTTP_access_control#Preflighted_requests" title="en/HTTP access control#Preflighted requests">preflighted cross-origin request</a>, in order to know whether it is safe to do it.
  <div class="note"><strong>Note:</strong> <a href="/En/HTTP_access_control#Preflighted_requests" title="en/HTTP access control#Preflighted requests">Preflighted cross-origin requests</a> cannot be done on servers which don't allow or support the OPTIONS method.</div>
 </li>
 <li>TRACE is a kind of ping between the client and the server (through eventual proxies).</li>
</ul>

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

<p>The CONNECT method is defined in <a class="external" href="https://tools.ietf.org/html/rfc2817" title="https://tools.ietf.org/html/rfc2817">RFC&nbsp;2817</a>.</p>

<h3 id="HTTP_Requests_Methods_in_HTML_Forms">HTTP&nbsp;Requests Methods in&nbsp;HTML&nbsp;Forms</h3>

<p>In HTML, different HTTP&nbsp;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&nbsp;specification.</p>

<div class="note"><strong>Note</strong>: The choice of a GET or POST method for HTML&nbsp;forms is not neutral. Because the GET method is a <a href="/en/HTTP#Safe_methods" title="https://developer.mozilla.org/en/HTTP#Safe_methods">safe method</a>, 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&nbsp;method should be used.</div>

<h2 id="HTTP_response_codes">HTTP response codes</h2>

<p>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:</p>

<ul>
 <li><dfn>Informational responses</dfn> (of the form <code>1xx</code>) are provisional responses. Most of the time neither the end user, nor the web developer or webmaster should have to bother with these. The most common is the <span style="font-family:courier new"><a href="/en/HTTP/HTTP_response_codes#100" title="en/HTTP/HTTP response codes#100">100 Continue</a></span> response, indicating that the client should continue to send its request.

  <div class="note"><strong>Note:</strong> No information response codes were defined in the HTTP/1.0, and therefore they must not be sent back when this version of the protocol is used.</div>
 </li>
 <li><dfn>Success responses</dfn> (of the form <code>2xx</code>) are for successfully processed requests. The <span style="font-family:courier new"><a href="/en/HTTP/HTTP_response_codes#200" title="en/HTTP/HTTP response codes#200">200 OK</a></span>&nbsp;response is by far the most common of these responses, but the <span style="font-family:courier new"><a href="/en/HTTP/HTTP_response_codes#206" title="en/HTTP/HTTP response codes#206">206 Partial Content</a></span> is also often seen when fetching a file or some media data like video or audio.</li>
 <li><dfn>Redirection responses</dfn> (of the form <code>3xx</code>) indicate that the resource that the client requested has moved and the server is not able to serve it directly. Most of these responses contain some location information telling where to find the requested resource; user-agents often then retrieve it without further user interaction. The most common responses of this type are <span style="font-family:courier new"><a href="/en/HTTP/HTTP_response_codes#301" title="en/HTTP/HTTP response codes#301">301 Moved Permanently</a></span>, indicating that the URI given is no longer valid and has been moved to another place, and <span style="font-family:courier new"><a href="/en/HTTP/HTTP_response_codes#302" title="en/HTTP/HTTP response codes#302">302 Found</a></span> which indicates that the resource has been <em>temporarily</em> moved to another place.
  <div class="note"><strong>Note:</strong> For webmasters, it is recommended to set up a <span style="font-family:courier new"><a href="/en/HTTP/HTTP_response_codes#301" title="en/HTTP/HTTP response codes#301">301 Moved Permanently</a></span> redirection when moving pages to another URI, during a site reorganization for example. That allows users following links to still reach the resource and it also teaches search engines and other services the new location of the resource, so that they can transfer their metadata to it. It is also important to add adequate cache headers to the <span style="font-family:courier new"><a href="/en/HTTP/HTTP_response_codes#301" title="en/HTTP/HTTP response codes#301">301 Moved Permanently</a></span> response so that this information is cached by the client and prevents it from making unnecessary requests to the original URI prior to fetching the resource itself.</div>
 </li>
 <li><dfn>Client error responses</dfn> (of the form <code>4xx</code>) indicate that the request sent by the client is either invalid, incomplete, or doesn't have enough rights to be performed. The most common such response is <span style="font-family:courier new"><a href="/en/HTTP/HTTP_response_codes#404" title="en/HTTP/HTTP response codes#404">404 Not Found</a></span> which is sent back when the URI requested doesn't exist, but a few others are often presented to the end user, like <span style="font-family:courier new"><a href="/en/HTTP/HTTP_response_codes#400" title="en/HTTP/HTTP response codes#400">400 Bad Request</a></span> sent when the request isn't a valid HTTP request (as this shouldn't happen but may indicate a bug into the user agent or, less likely, the server) or <span style="font-family:courier new"><a href="/en/HTTP/HTTP_response_codes#403" title="en/HTTP/HTTP response codes#403">403 Forbidden</a></span>, sent when the client request a resource that does exist but isn't allowed to be transmitted (like a directory content).</li>
 <li><dfn>Server error responses</dfn> (of the form <code>5xx</code>) indicate that the server had a problem handling the valid client request. The two most common such responses are <span style="font-family:courier new"><a href="/en/HTTP/HTTP_response_codes#500" title="en/HTTP/HTTP response codes#500">500 Internal Server Error</a></span>, a generic error code indicating a bug in the server or <span style="font-family:courier new"><a href="/en/HTTP/HTTP_response_codes#503" title="en/HTTP/HTTP response codes#503">503 Service Unavailable</a></span> indicating that the server cannot process the request due to a temporary problem, like a disabled service for maintenance purposes or the non-availability of a database.</li>
</ul>

<p>A web developer shouldn't encounter many other response codes, but people building requests using the <code><a href="/en/nsIXMLHttpRequest" title="en/XMLHttpRequest">XMLHTTPRequest</a></code> function may hit <a href="/en/HTTP/HTTP_response_codes" title="en/HTTP/HTTP response codes">less usual response codes</a>.</p>

<h3 id="More_on_redirection_responses">More on redirection responses</h3>

<p>Starting in Gecko 9.0 {{ geckoRelease("9.0") }}, redirections (such as 301 and 307) that specify a <code>javascript:</code> 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.</p>

<h2 id="HTTP_headers">HTTP headers</h2>

<p>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.</p>

<p>Headers are grouped according the context in which they may appear:</p>

<dl>
 <dt>General headers</dt>
 <dd>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 been added without increasing the version number of the HTTP&nbsp;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") }}.</dd>
 <dt>Request headers</dt>
 <dd>These headers give more precise information about the resource to be fetched or about the client itself. Among them one find <a href="/en/HTTP_Caching_FAQ" title="en/HTTP Caching FAQ">cache-related headers</a>, 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 <em>entity headers</em>.</dd>
 <dt>Response headers</dt>
 <dd>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 <em>entity headers</em>.</dd>
 <dt>Entity headers</dt>
 <dd>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.</dd>
</dl>

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

<dl>
 <dt>End-to-end headers</dt>
 <dd>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.</dd>
 <dt>Hop-by-hop headers</dt>
 <dd>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.</dd>
</dl>

<p>In order to learn about the specific semantic of each header, see its entry in the <a href="/en/HTTP/Headers" title="en/HTTP/Headers">comprehensive list of HTTP&nbsp;headers</a>.</p>

<h3 id="Useful_request_headers">Useful request headers</h3>

<p>Among the numerous <a href="/en/HTTP/Headers" title="en/HTTP/Headers">HTTP request headers</a>, several are especially useful when set correctly. If you are building your own requests, by using <code><a href="/en/DOM/XMLHttpRequest" title="en/XMLHTTPRequest">XMLHTTPRequest</a></code> or when writing an extension and sending <a href="/en/Setting_HTTP_request_headers" title="en/Setting HTTP request headers">custom HTTP requests via XPCOM</a>, then it is important to ensure the presence of headers that are often set by browsers based on the preferences of the user.</p>

<dl>
 <dt>Controlling the language of the resource</dt>
 <dd>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&nbsp;requests, to include such a header too.</dd>
 <dt>Using conditional GET</dt>
 <dd>Caching is a major tool to accelerate the display of web pages. Even when parts of a webpage are refreshed via an&nbsp;<code><a href="/en/DOM/XMLHttpRequest" title="en/XMLHTTPRequest">XMLHTTPRequest</a></code>:, 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.</dd>
</dl>

<h3 id="Useful_response_headers">Useful response headers</h3>

<p>The configuration of a web server is a critical part to ensure good performance and optimal security of a web site. Among the <a href="/en/HTTP/Headers" title="en/HTTP/Headers">numerous HTTP response headers</a>, several are of specific importance and should be configured on the server</p>

<h4 id="Restricting_framing">Restricting framing</h4>

<p>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 <a href="/en/The_X-FRAME-OPTIONS_response_header" title="en/The X-FRAME-OPTIONS response header"><code>X-Frame-Options:</code> response header</a>. By setting it with the value <code>DENY</code>, 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 <a href="/en/Security/CSP/Introducing_Content_Security_Policy" title="en/Security/CSP/Introducing Content Security Policy">Content Security Policies</a>, may be helpful too.</p>

<h4 id="Compression">Compression</h4>

<p>Minimizing the amount of data transferred accelerates the display of a web page. Though most techniques, like <a href="/en/CSS/CSS_Sprites" title="en/CSS/CSS Sprites">CSS Sprites</a>, 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 <a class="external" href="https://httpd.apache.org/docs/2.0/mod/mod_deflate.html" title="https://httpd.apache.org/docs/2.0/mod/mod_deflate.html">mod_deflate module</a>.</p>

<div class="note"><strong>Note:</strong> 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.</div>

<h4 id="Controlling_cache">Controlling cache</h4>

<p><a href="/en/HTTP_Caching_FAQ" title="en/HTTP Caching FAQ">HTTP&nbsp;Caching</a> 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:</p>

<ul>
 <li>Any static resource provides an {{ httpheader("Expires") }} response header that is set to far in the future. That way, the resource may stay in the cache until the user-agent flushes it for its own reasons (like reaching its cache size limit).
  <div class="note"><strong>Note:&nbsp;</strong>On Apache, use the ExpiresDefault directive in your .htaccess to define a relative expires: <code>ExpiresDefault "access plus 1 month"</code>.</div>
 </li>
 <li>Any dynamic resource provides a {{ httpheader("Cache-control") }} response header. Theoretically, any HTTP request done through a <a href="/en/HTTP#Safe_Methods" title="en/HTTP#Safe Methods">safe method</a> (GET or HEAD) or even through a solely <a href="/en/HTTP#Idempotent_Methods" title="en/HTTP#Idempotent Methods">idempotent one</a> (DELETE, PUT) may be cached; but in practice careful study is needed to determine if the caching of the response may lead to inappropriate side-effects.</li>
</ul>

<h4 id="Setting_the_correct_MIME_types">Setting the correct MIME types</h4>

<p>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&nbsp;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.</p>

<div class="note"><strong>Note: </strong>

<ul>
 <li>On Apache, one can match file extensions with a given MIME type in the .htaccess using the <font face="Verdana,Helvetica,Arial"><span style="font-family:courier new"><code>AddType</code></span> type directive like</font><code> AddType image/jpeg jpg.</code></li>
 <li>Most web servers send unknown-type resources using the default <code>application/octet-stream</code> MIME&nbsp;type; for security reasons, most browsers, like Firefox, do not allow setting a custom default action for such resources and force the user to store it to disk in order to use it. Some common cases of often incorrectly configured servers happens for the following file types:
  <ul>
   <li>
    <p>Rar-encoded files. The ideal would be to be able to set the real type of the encoded files; this often is not possible (as it may not be known to the server and these files may contains several resource of different types). In that case, configure the server to send the <code>application/x-rar-compressed </code>MIME type or some users won't be able to define a useful default action for them.</p>
   </li>
   <li>
    <p>Audio and video files. Only resources with the proper MIME&nbsp;Type will be recognized and played, using a {{ HTMLElement("video") }} or {{ HTMLElement("audio") }} elements. Be sure to <a href="/En/Media_formats_supported_by_the_audio_and_video_elements" title="En/Media formats supported by the audio and video elements">use the correct MIME type for audio and video resources</a>.</p>
   </li>
   <li>
    <p>Proprietary file types. Pay special attention when serving a proprietary file type. Be sure not to forget to add an x-prefixed type for it; otherwise, special handling won't be possible. This is especially true with resources using the <a class="external" href="https://en.wikipedia.org/wiki/Keyhole_Markup_Language" title="https://en.wikipedia.org/wiki/Keyhole_Markup_Language">Keyhole Markup Language</a>, which should be served as <code>application/vnd.google-earth.kml+xml </code>for an optimal user experience.</p>
   </li>
  </ul>
 </li>
</ul>
</div>

<div class="section">
<h2 class="Community" id="Community" name="Community">Community</h2>

<ul>
 <li>View Mozilla forums... {{ DiscussionList("dev-web-development", "mozilla.dev.web.development") }}</li>
</ul>

<h2 class="Tools" id="Tools" name="Tools">Tools</h2>

<ul>
 <li><a href="/en-US/docs/Web/API/XMLHttpRequest#getAllResponseHeaders()" title="/en-US/docs/Web/API/XMLHttpRequest#getAllResponseHeaders()"><code>XMLHttpRequest.prototype.getAllResponseHeaders()</code></a></li>
</ul>

<p><span class="alllinks"><a href="/en-US/docs/tag/HTTP:Tools" title="tag/HTTP:Tools">View All...</a></span></p>

<h2 class="Related_Topics" id="Related_Topics" name="Related_Topics">Related Topics</h2>

<ul>
 <li><a href="/en-US/docs/Web/API/document.cookie" title="/en-US/docs/Web/API/document.cookie">document.cookie</a></li>
 <li><a href="/en-US/docs/Web/API/XMLHttpRequest" title="/en-US/docs/Web/API/XMLHttpRequest"><code>XMLHttpRequest</code></a></li>
</ul>
</div>

<h2 id="See_also">See also</h2>

<ul>
 <li><a href="/En/Controlling_DNS_prefetching" title="En/Controlling DNS prefetching">Controlling DNS&nbsp;prefetching</a></li>
 <li>The <a href="/en/HTTP_Pipelining_FAQ" title="https://developer.mozilla.org/en/HTTP_Pipelining_FAQ">HTTP pipelining FAQ</a></li>
 <li><a href="/en/Web_Development/HTTP_cookies" title="HTTP cookies">HTTP cookies</a></li>
 <li><a href="/en-US/docs/HTTP/Headers" title="/en-US/docs/HTTP/Headers">HTTP Headers</a></li>
 <li><a href="/en-US/docs/HTTP/Basic_access_authentication" title="/en-US/docs/HTTP/Basic_access_authentication">Basic access authentication</a></li>
 <li><a href="/en-US/docs/HTTP/Access_control_CORS" title="/en-US/docs/HTTP/Access_control_CORS">HTTP access control (CORS)</a></li>
</ul>

<p>{{ languages( { "ja": "ja/HTTP"} ) }}</p>
Вернуть эту версию