HTTP location
The HTTP Location header field is a response header in the Hypertext Transfer Protocol (HTTP) that specifies a URI reference to a resource associated with the response, primarily used to indicate the location of a newly created resource or to redirect the recipient to an alternative URI.[1] Its syntax is defined asLocation = URI-reference, where the value is a single URI-reference that may be absolute or relative, resolved against the effective request URI if relative.[1] This header derives its specific meaning from the context of the request method and response status code, making it essential for standard HTTP behaviors like resource relocation and creation notifications.[1]
In practice, the Location header is most commonly associated with the 201 Created status code, where it is recommended to identify the primary URI of the resource resulting from a successful creation operation, such as after a POST request that generates a new entity.[2] For redirection purposes, it appears in responses with 3xx status codes (Redirection), including 301 Moved Permanently, 302 Found, 303 See Other, 307 Temporary Redirect, and 308 Permanent Redirect, to specify the target URI for the client or user agent to follow.[3] In these cases, the header guides automatic or manual redirection, with the choice of HTTP method for the subsequent request depending on the original method and the redirection type— for instance, GET is typically used after 303 regardless of the initial method. If the Location URI lacks a fragment identifier, it inherits the one from the original request URI to preserve context.[1]
The header's role extends beyond strict redirection; it can also appear in other contexts, such as with the 202 Accepted status code to point to a resource tracking an asynchronous operation, though this is less standardized. Defined initially in HTTP/1.1 specifications and refined in subsequent updates, the Location header ensures interoperability across HTTP versions by focusing on semantic clarity rather than transport details.[1] User agents, including web browsers, have supported it universally since the early 2000s, enabling seamless navigation in web applications and APIs.
Overview
Definition
The Location header is a response header field in the Hypertext Transfer Protocol (HTTP) that specifies a URI reference to identify a specific resource in relation to the response, serving as an indicator for the target resource in scenarios such as redirection or resource location.[4] It provides a means for servers to communicate the URI of a resource to clients, enabling appropriate navigation or reference without requiring additional requests in certain contexts.[4] Defined within the semantics of HTTP as per RFC 9110, the Location header is integral to the protocol's response handling, where it is mandatory in specific response contexts to direct client behavior effectively, such as guiding user agents toward a designated resource.[4] This ensures interoperability and standardized interpretation across HTTP implementations, with the header's presence influencing how clients process and act upon server responses.[4] Technically, the Location header is classified as a single-value field, meaning it conveys exactly one URI reference rather than a list, and its value adheres to the URI-reference production rule from RFC 3986, allowing for either an absolute URI or a relative reference that resolves against the effective request URI.[4] This structure supports flexibility in URI specification while maintaining precision in resource identification.[4]Primary Purposes
The Location header field in HTTP serves primarily to indicate the URI of a resource to which the client should redirect or reference following a server response. In redirection scenarios, it instructs the user agent, such as a web browser, to retrieve a different resource, often to handle cases where the requested resource has been moved, renamed, or temporarily relocated to an alternative endpoint. This mechanism enables seamless navigation without requiring the client to know the new location in advance.[1] Another key purpose of the Location header is to identify the URI of a newly created resource in response to successful creation requests, such as those using POST or PUT methods. Upon successful creation, the server includes the Location header to provide the canonical URI for the new resource, allowing the client to immediately access, bookmark, or further interact with it. This facilitates resource management in web applications and APIs by establishing a persistent identifier for the created entity.[1] Unlike the Content-Location header, which specifies the URI of the specific representation of content included in the response body (e.g., for variant negotiation), the Location header exclusively points to the target URI for redirection or the primary URI of a newly created resource. This distinction ensures that Location focuses on navigational or identificatory intent rather than describing the content's origin or variant.[1][5] User agents are expected to resolve the URI provided in the Location header relative to the original request URI if it is relative, and to follow it automatically in appropriate contexts, thereby maintaining the flow of the HTTP interaction without user intervention. This behavior promotes efficient resource location and retrieval in distributed systems.[1]Syntax and Format
Header Structure
The Location header field in HTTP provides a means to specify a URI reference associated with the response, typically indicating the location of a redirected or newly created resource. According to RFC 9110, its syntax is defined asLocation = URI-reference, where the value adheres to the Augmented Backus-Naur Form (ABNF) notation and represents a single URI reference as specified in RFC 3986.[6][7] This allows for absolute URIs, relative references, or URI references including fragments, enabling flexible indication of resource locations without mandating full absolute paths in every case.
In HTTP message format, the header appears as a standard response header field line, structured as Location: <URI-reference>, where the field name "Location" is case-insensitive per HTTP conventions in RFC 9110.[8] Leading and trailing whitespace around the field value is typically ignored or trimmed during parsing, though the value itself should not include unencoded control characters to maintain compliance. Servers generate this header in responses where redirection or resource creation semantics apply, ensuring the value is a well-formed URI reference to avoid interoperability issues.
A key constraint is that the Location value must constitute a valid URI-reference; malformed or invalid values can result in clients ignoring the header, issuing errors, or failing to process the intended redirection or location indication, as clients are not obligated to handle non-conforming URIs.[6] Regarding encoding, URI components within the value follow the percent-encoding rules outlined in RFC 3986 for representing special or reserved characters, such as spaces (encoded as %20) or non-ASCII characters, to ensure safe transmission over HTTP.[9] This encoding preserves the integrity of the reference while allowing relative forms that resolve against the request's effective URI when necessary.
URI Types and Resolution
The Location header field in HTTP accepts a URI reference, which may be either an absolute URI or a relative reference. An absolute URI provides the complete resource identifier, including the scheme (e.g.,https), authority (host and port), and path (e.g., https://example.com/path), enabling resolution without additional context.[1] This form ensures unambiguous targeting of the resource, as defined in the generic URI syntax.[10]
Relative references in the Location header take two primary forms: path-relative or absolute-path. A path-relative reference consists of path segments without a leading slash (e.g., newpath or subdir/newpath), while an absolute-path reference begins with a slash (e.g., /newpath). These are not standalone and require resolution against a base URI.[1] Per the HTTP semantics, relative references are resolved relative to the target URI of the original request, rather than any URI associated with the response itself.[1]
Resolution follows the algorithm in URI generic syntax, where the base URI (the request's target URI) supplies missing components like scheme and authority.[11] For an absolute-path relative reference, the path replaces the base path entirely while inheriting the scheme and authority (e.g., /newpath appended to the host from the base). Path-relative references merge with the base path by appending segments after removing the last base segment (e.g., newpath added to the end of the base path). Dot-segments such as ../ navigate upward in the directory hierarchy during normalization, effectively removing preceding path segments (e.g., ../ ascends one level). The resulting URI undergoes dot-segment removal to produce a normalized absolute form.[12]
When processing redirects via the Location header, clients normalize the resolved URI and follow the chain, using the original request URI as the base for each step. Browsers and user agents typically limit redirect chains to prevent loops, with a common recommendation of no more than 5 hops, though implementations often allow up to 30.[1] This resolution ensures consistent resource targeting across HTTP responses.[1]
Usage in Responses
With Redirection Status Codes
The Location header is mandatory in HTTP responses using the 3xx-series redirection status codes 301 (Moved Permanently), 302 (Found), 303 (See Other), 307 (Temporary Redirect), and 308 (Permanent Redirect), where it specifies the URI of the new or alternative resource that the client should access to fulfill the original request.[4] These codes signal to the client that further action is required, with the Location header providing the target URI to enable seamless resource relocation, either temporarily or permanently.[13] Client behavior upon receiving a 3xx response with Location varies by the original request method and the specific status code. For safe methods such as GET and HEAD, clients SHOULD automatically follow the redirect to the URI in Location, preserving the method unless the code specifies otherwise (e.g., 303 mandates conversion to GET).[14][15][16] For 307 and 308, if redirection occurs, the original method and request body (if present) must be preserved.[17][18] In contrast, for unsafe methods like POST, clients SHOULD NOT automatically redirect without user confirmation or explicit configuration, to prevent unintended state changes; if redirection occurs, 307 and 308 require preserving the method and body, while 303 always converts to GET without reusing the body.[19][16][17] An exception applies to the 304 (Not Modified) status code, which does not use the Location header; instead, it instructs the client to reuse its cached representation of the original request URI without any redirection.[20] To prevent infinite loops in redirect chains, clients SHOULD detect and intervene in cyclical redirections, typically by tracking the sequence of URIs followed and imposing implementation-specific limits on the number of redirects (e.g., via hop counts).[13]With Creation Status Codes
The Location header plays a crucial role in HTTP responses indicating successful resource creation, particularly with status codes that affirm the establishment of new resources on the server. In a 201 (Created) response, the server SHOULD include the Location header to specify the URI of the primary resource created by the request, enabling clients to reference and interact with it directly.[2] This usage commonly arises from POST requests that generate new resources or PUT requests that create them when the target does not previously exist, fulfilling the protocol's semantics for affirmative creation outcomes.[21] For asynchronous processing scenarios, the 202 (Accepted) status code may optionally incorporate the Location header to point to a resource that tracks the status of the pending operation, such as a queued task or job.[22] When present, this URI allows clients to poll or subscribe to updates on the request's progress without assuming immediate completion, though its inclusion depends on whether the server provides such a monitoring endpoint.[22] Best practices for implementing the Location header in these contexts emphasize using a canonical, absolute URI that is immediately accessible to clients, avoiding relative references unless resolved against the request's effective URI.[1] This approach aligns with RESTful API design principles, where the header facilitates resource retrieval via subsequent GET requests, promoting stateless interactions and efficient discovery of newly created entities.[23] Clients are expected to treat the provided URI as the definitive identifier for the new resource, using it to access metadata, content, or perform further operations without needing additional queries to locate it.[24]Examples
Absolute URI Example
In a typical redirection scenario, a client issues a GET request to the resource at/old on a server. The server responds with a 301 Moved Permanently status code, indicating that the requested resource has been permanently relocated, and includes an absolute URI in the Location header to specify the new target.[1] This setup ensures the client can immediately follow the redirect without needing to resolve any relative references against the original request's base URI.[1]
A full example of such a response header follows:
Here, the absolute URIHTTP/1.1 301 Moved Permanently Location: [https](/page/HTTPS)://[example.com](/page/Example.com)/newpage.[html](/page/HTML)HTTP/1.1 301 Moved Permanently Location: [https](/page/HTTPS)://[example.com](/page/Example.com)/newpage.[html](/page/HTML)
https://example.com/newpage.html fully specifies the scheme, authority, and path, allowing the client to directly access the new resource.[1]
Upon receiving this response, the client resolves and issues a subsequent request to the absolute URI provided, operating independently of the original request's base (such as the host or scheme from which /old was requested).[1] This direct resolution promotes reliability in redirection, as the target is unambiguous and self-contained.[25]
Absolute URIs in the Location header are particularly ideal for scenarios involving cross-domain redirects or changes in protocol scheme, such as migrating from HTTP to HTTPS, where preserving the exact target details is essential to avoid resolution errors or security mismatches.[1]
Relative URI Example
In HTTP responses, the Location header can employ relative URI references to indicate a redirection target, which are resolved by the client relative to the effective request URI as defined in RFC 3986.[26] Consider a client requesting the resource athttps://example.com/blog/post1. The server might respond with a 302 Found status code and a Location header containing a relative URI such as /newpost, an absolute-path reference that points to a new location within the same authority.[1]
The response header would appear as follows:
Upon receiving this, the client resolvesHTTP/1.1 302 Found Location: /newpostHTTP/1.1 302 Found Location: /newpost
/newpost against the original request URI, resulting in the absolute URI https://example.com/newpost.
Relative URIs can also use path-relative forms, such as ../category, to navigate up the directory hierarchy. For the same request to https://example.com/blog/post1, the Location header ../category resolves by removing the post1 segment (due to ..), leaving /blog/, then appending category, yielding https://example.com/blog/category.[11]
This approach with relative URIs in the Location header reduces redundancy by omitting the scheme and authority for same-origin redirects, thereby shortening the header value and simplifying server configuration, while user agents handle the normalization to absolute form transparently.
Creation URI Example
The Location header is commonly used with the 201 Created status code to indicate the URI of a newly created resource. For instance, a client sends a POST request tohttps://example.com/users to create a new user. The server processes the request, creates the resource, and responds with a 201 status and an absolute URI in the Location header pointing to the new resource.[2]
A full example of such a response header follows:
Here, the absolute URIHTTP/1.1 201 Created Location: https://example.com/users/123HTTP/1.1 201 Created Location: https://example.com/users/123
https://example.com/users/123 identifies the primary URI of the created user resource. The client can then use this URI for further operations, such as retrieving the resource details. Relative URIs can also be used in this context, resolved against the request's target URI.
Standards and Evolution
Key RFC Specifications
The Location header field in HTTP was initially defined in RFC 2616, published in June 1999 as a Standards Track document that specified HTTP/1.1 semantics.[27] This RFC established the header as a response field used to redirect recipients to a location other than the request URI, particularly in 201 (Created) responses to identify new resources and in 3xx redirection status codes such as 301 (Moved Permanently) and 302 (Found).[28] It mandated that the Location value consist of a single absolute URI to ensure clients could independently resolve the target without context dependency, with syntax defined asLocation = "Location" ":" absoluteURI.[28] RFC 2616 was later obsoleted by the HTTP/1.1 specification updates in 2014.[27]
RFC 7231, published in June 2014 as part of the revised HTTP/1.1 core semantics and content on the Standards Track, refined the Location header's definition to enhance flexibility.[29] It describes the header as a means to refer to a specific resource in relation to the response, used in 201 responses to denote the primary created resource and in 3xx responses to indicate the redirection target.[30] Unlike its predecessor, RFC 7231 permits URI references, including relative forms resolved against the effective request URI, with syntax Location = URI-reference.[30] This adjustment supports fragments and relative paths while maintaining interoperability for absolute URIs.[30]
The syntax for URIs in the Location header relies on RFC 3986, published in January 2005 as a Standards Track document defining the generic URI syntax.[7] This RFC outlines URI components such as scheme, authority, path, query, and fragment, using ABNF notation like URI-reference = URI / relative-ref to specify absolute URIs and relative references resolvable via a base URI.[31] It provides the foundational rules for parsing and normalizing Location values in HTTP, ensuring consistent resolution across implementations.[32]
RFC 9110, published in June 2022 as an Internet Standards Track document on HTTP semantics, consolidates and updates the Location header specifications from prior RFCs including 7231.[33] It reaffirms the header's role in 201 responses for new resource URIs and 3xx responses for redirection targets, retaining the URI-reference syntax while clarifying rules for automatic client redirection based on status codes like 301, 302, and 303.[6] This consolidation separates semantics from transport details, obsoleting RFC 7231 and related documents to streamline HTTP evolution.[34]