RFC 2396

Uniform Resource Identifiers (URI): Generic Syntax

๐Ÿ“… published August 1998, from ietf

RFC 2396: Uniform Resource Identifiers (URI): Generic Syntax ๐Ÿฆ‹

Okay bestie, this is the RFC that lays out the generic syntax for URIs, the little strings that name stuff all over the internet ๐Ÿ’– It's an Standards Track doc from August 1998, and the authors are T. Berners-Lee (MIT/LCS), R. Fielding (U.C. Irvine), and L. Masinter (Xerox Corporation) ๐Ÿ‘‘. It updates RFC 1808 and RFC 1738 โœจ and it's the one that merges and replaces their generic definitions. Iconic lineup, no cap ๐Ÿ’…


Status of this Memo

This document is an Internet standards track protocol for the Internet community, and it asks for discussion and suggestions for improvements ๐Ÿซถ For the standardization state and status of this protocol, check the current edition of the "Internet Official Protocol Standards" (STD 1). Distribution of this memo is unlimited ๐ŸŒธ

Copyright (C) The Internet Society (1998). All Rights Reserved. ๐Ÿ’œ

IESG Note

Okay, this one's a heads up ๐Ÿ™ˆ The paper describes a "superset" of operations that can be applied to URI. It has both a grammar and a description of basic functionality, so to figure out what counts as a valid URI, you need to study both the grammar and the description. Some of the functionality isn't applicable to every URI scheme, and some operations only work when certain media types are retrieved using the URI, no matter which scheme is used. Main character energy, but it's complicated ๐Ÿ’€

Abstract

A Uniform Resource Identifier (URI) is a compact string of characters for identifying an abstract or physical resource. โœจ This document defines the generic syntax of URI, including both absolute and relative forms, plus guidelines for using them. It revises and replaces the generic definitions in RFC 1738 and RFC 1808 ๐ŸŽ€

It also defines a grammar that's a superset of all valid URI, so an implementation can parse the common components of a URI reference without knowing the scheme-specific requirements of every possible identifier type ๐Ÿงš It does not define a generative grammar for URI. That job belongs to the individual specifications of each URI scheme ๐Ÿ“

1. Introduction โœจ

Okay so URI give us a simple, extensible way to identify a resource ๐Ÿฆ‹ This syntax and semantics come from concepts introduced by the World Wide Web global information initiative, whose use of these objects dates from 1990 and is described in "Universal Resource Identifiers in WWW" [RFC1630]. The design is meant to meet the recommendations in "Functional Recommendations for Internet Resource Locators" [RFC1736] and "Functional Requirements for Uniform Resource Names" [RFC1737]. Iconic research energy ๐Ÿ“š

This document updates and merges "Uniform Resource Locators" [RFC1738] and "Relative Uniform Resource Locators" [RFC1808] to define a single, generic syntax for all URI ๐Ÿ’– It leaves out the parts of RFC 1738 that defined the specific syntax of individual URL schemes. Those parts will be updated as separate documents, and so will the process for registering new URI schemes ๐ŸŒˆ It also doesn't cover dealing with characters outside of the US-ASCII character set [ASCII]. Those recommendations live in a separate document ๐Ÿซถ

All significant changes from the prior RFCs are noted in Appendix G. ๐Ÿ“

1.1 Overview of URI

Bestie, URI have a few defining traits ๐Ÿ‘‘

  • Uniform ๐Ÿ’… Uniformity gives us a bunch of perks. It lets different types of resource identifiers be used in the same context, even when the mechanisms for accessing those resources differ. It allows uniform semantic interpretation of common syntactic conventions across different types of resource identifiers. It lets new types of resource identifiers show up without messing with how existing identifiers are used. And it lets identifiers be reused in many different contexts, so new applications or protocols can tap into a pre-existing, large, and widely-used set of resource identifiers. Slay ๐ŸŒธ
  • Resource ๐Ÿฆ‹ A resource can be anything that has identity. Familiar examples include an electronic document, an image, a service (e.g., "today's weather report for Los Angeles"), and a collection of other resources. Not all resources are network "retrievable"; for example, human beings, corporations, and bound books in a library can also be considered resources ๐Ÿ™ˆ

The resource is the conceptual mapping to an entity or set of entities, not necessarily the entity that corresponds to that mapping at any particular instance in time. So a resource can stay constant even when its content (the entities it currently corresponds to) changes over time, as long as the conceptual mapping doesn't change in the process โœจ

  • Identifier ๐Ÿ”ฅ An identifier is an object that can act as a reference to something that has identity. For URI, the object is a sequence of characters with a restricted syntax ๐Ÿ’œ

Once you've identified a resource, a system can perform a variety of operations on it, the kind of thing you'd describe with words like โ€˜accessโ€™, โ€˜updateโ€™, โ€˜replaceโ€™, or โ€˜find attributesโ€™ ๐Ÿ’…

1.2. URI, URL, and URN

A URI can be classified as a locator, a name, or both ๐Ÿงš The term "Uniform Resource Locator" (URL) refers to the subset of URI that identify resources through a representation of their primary access mechanism (e.g., their network "location"), instead of identifying the resource by name or by some other attribute(s) of that resource. The term "Uniform Resource Name" (URN) refers to the subset of URI that are required to remain globally unique and persistent, even when the resource ceases to exist or becomes unavailable ๐ŸŒˆ

The URI scheme (Section 3.1) defines the namespace of the URI, so it may further restrict the syntax and semantics of identifiers using that scheme ๐Ÿ“ This specification defines the elements of URI syntax that are either required of all URI schemes or common to many of them. That gives us the syntax and semantics needed for a scheme-independent parsing mechanism for URI references, so the scheme-dependent handling of a URI can wait until the scheme-dependent semantics are actually needed. We use the term URL below when describing syntax or semantics that only apply to locators ๐ŸŽ€

Although many URL schemes are named after protocols, that doesn't mean the only way to access the URL's resource is through the named protocol. Gateways, proxies, caches, and name resolution services might be used to reach some resources, no matter what protocol they originally came from. And resolving some URL may require more than one protocol (for example, both DNS and HTTP are typically used to access an "http" URL's resource when it can't be found in a local cache) ๐Ÿฆ‹

A URN differs from a URL in that its primary purpose is persistent labeling of a resource with an identifier ๐Ÿ’– That identifier is drawn from one of a set of defined namespaces, each with its own name structure and assignment procedures. The "urn" scheme has been reserved to establish the requirements for a standardized URN namespace, as defined in "URN Syntax" [RFC2141] and its related specifications ๐Ÿ‘‘

Most of the examples in this specification demonstrate URL, since they allow the most varied use of the syntax and often have a hierarchical namespace. A parser of URI syntax can parse both URL and URN references as a generic URI. Once the scheme is determined, the scheme-specific parsing can be done on the generic URI components. In other words, the URI syntax is a superset of the syntax of all URI schemes ๐Ÿซถ

1.3. Example URI

Here are some URI that are in common use ๐ŸŒธ

ftp://ftp.is.co.za/rfc/rfc1808.txt
   -- ftp scheme for File Transfer Protocol services

gopher://spinaltap.micro.umn.edu/00/Weather/California/Los%20Angeles
   -- gopher scheme for Gopher and Gopher+ Protocol services

http://www.math.uio.no/faq/compression-faq/part1.html
   -- http scheme for Hypertext Transfer Protocol services

mailto:mduerst@ifi.unizh.ch
   -- mailto scheme for electronic mail addresses

news:comp.infosystems.www.servers.unix
   -- news scheme for USENET news groups and articles

telnet://melvyl.ucop.edu/
   -- telnet scheme for interactive services via the TELNET Protocol

1.4. Hierarchical URI and Relative Forms

An absolute identifier refers to a resource independent of the context in which the identifier is used. In contrast, a relative identifier refers to a resource by describing the difference, within a hierarchical namespace, between the current context and an absolute identifier of the resource ๐Ÿงš

Some URI schemes support a hierarchical naming system, where the hierarchy of the name is denoted by a "/" delimiter separating the components in the scheme. This document defines a scheme-independent relative' form of URI reference that can be used together with a base' URI (of a hierarchical scheme) to produce another URI. The syntax of hierarchical URI is described in Section 3, and the relative URI calculation is described in Section 5 ๐ŸŽ€๐Ÿ’…


1.5. URI Transcribability โœจ

Bestie, the URI syntax was literally designed around global transcribability ๐Ÿ’…. A URI is a sequence of characters from a very limited set: the letters of the basic Latin alphabet, digits, and a few special characters. It can show up in lots of forms, like ink on paper, pixels on a screen, or a sequence of octets in a coded character set ๐ŸŽ€. How a URI gets interpreted depends only on the characters used, not on how those characters are represented in a network protocol ๐Ÿงš.

Okay, the scenario is so iconic ๐Ÿฅน. Imagine Sam and Kim, two colleagues chilling in a pub at an international conference and swapping research ideas ๐Ÿ“. Sam asks Kim where to find more info, so Kim writes the URI for the research site on a napkin ๐Ÿซถ. Back home, Sam pulls out the napkin, types the URI into a computer, and boom, the info Kim meant pops right up ๐Ÿ˜ญ. Main character energy, no cap ๐Ÿฆ‹.

That scenario shows a few design concerns:

  • A URI is a sequence of characters, which is not always represented as a sequence of octets.
  • A URI may be transcribed from a non-network source, and thus should consist of characters that are most likely to be able to be typed into a computer, within the constraints imposed by keyboards (and related input devices) across languages and locales.
  • A URI often needs to be remembered by people, and it is easier for people to remember a URI when it consists of meaningful components.

These concerns aren't always in alignment, ngl ๐Ÿ’€. For example, the most meaningful name for a URI component might need characters that some systems just can't type. The ability to transcribe the resource identifier from one medium to another was considered more important than having its URI made of the most meaningful components ๐Ÿ‘‘. In local and regional contexts, and with improving technology, users might benefit from a wider range of characters ๐ŸŒˆ. That kind of use is not defined in this document, though ๐Ÿ™ˆ.

1.6. Syntax Notation and Common Elements ๐Ÿ“

This document uses two conventions to describe and define URI syntax ๐Ÿ“. The first one is called the layout form. It's a general description of the order of components and component separators, like this:

<first>/<second>;<third>?<fourth>

Component names go in angle-brackets, and any characters outside angle-brackets are literal separators. Whitespace should be ignored. These descriptions are used informally and do not define the syntax requirements, so don't treat them as the rulebook ๐Ÿ’–.

The second convention is a BNF-like grammar that defines the formal URI syntax ๐Ÿ”ฅ. The grammar is that of [RFC822], except that "|" is used to designate alternatives. Here's the quick version:

  • Rules are separated from definitions by an equal "=".
  • Indentation is used to continue a rule definition over more than one line.
  • Literals are quoted with "".
  • Parentheses "(" and ")" are used to group elements.
  • Optional elements are enclosed in "[" and "]" brackets.
  • Elements may be preceded with <n>* to designate n or more repetitions of the following element, and n defaults to 0.

Here's the twist that makes this grammar special โœจ. Lots of specs use BNF-like grammars to define the bytes (octets) a protocol allows, but the URI grammar is defined in terms of characters. Each literal in the grammar corresponds to the character it represents, not to the octet encoding of that character in any particular coded character set. How a URI is represented in bits and bytes on the wire depends on the character encoding of the protocol that transports it, or on the charset of the document that contains it ๐Ÿง .

The following definitions are common to many elements:

alpha    = lowalpha | upalpha

lowalpha = "a" | "b" | "c" | "d" | "e" | "f" | "g" | "h" | "i" |
           "j" | "k" | "l" | "m" | "n" | "o" | "p" | "q" | "r" |
           "s" | "t" | "u" | "v" | "w" | "x" | "y" | "z"

upalpha  = "A" | "B" | "C" | "D" | "E" | "F" | "G" | "H" | "I" |
           "J" | "K" | "L" | "M" | "N" | "O" | "P" | "Q" | "R" |
           "S" | "T" | "U" | "V" | "W" | "X" | "Y" | "Z"

digit    = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" |
           "8" | "9"

alphanum = alpha | digit

The complete URI syntax is collected in Appendix A ๐Ÿ“š.


2. URI Characters and Escape Sequences ๐Ÿฆ‹

URIs use a restricted set of characters, mostly picked to help with transcribability and usability, both in computer systems and in non-computer communications ๐Ÿ’œ. Characters that are conventionally used as delimiters around URIs were left out. The restricted set is made up of digits, letters, and a few graphic symbols that were chosen from the ones common to most character encodings and input facilities that Internet users have access to โญ.

uric          = reserved | unreserved | escaped

Inside a URI, characters are either used as delimiters or to represent strings of data (octets) inside the delimited parts ๐ŸŽ€. Octets are either represented directly by a character (using the US-ASCII character for that octet [ASCII]) or by an escape encoding. We'll get into that below ๐Ÿ‘€.

2.1 URI and non-ASCII characters ๐ŸŒธ

The relationship between URIs and characters has caused a lot of confusion, especially for characters that aren't part of US-ASCII ๐Ÿ˜ญ. To sort it out, it helps to tell apart a "character" (a distinguishable semantic entity) and an "octet" (an 8-bit byte). There are two mappings: one from URI characters to octets, and a second from octets back to original characters:

URI character sequence->octet sequence->original character sequence

A URI is represented as a sequence of characters, not as a sequence of octets. That's because a URI might be "transported" by means that don't go through a computer network, like being printed on paper or read over the radio ๐Ÿ“ป.

A URI scheme may define a mapping from URI characters to octets, but whether it does depends on the scheme ๐Ÿงš. Usually, inside a delimited component of a URI, a sequence of characters can be used to represent a sequence of octets. For example, the character "a" represents the octet 97 (decimal), while the character sequence "%", "0", "a" represents the octet 10 (decimal) ๐Ÿ”ข.

There's a second translation for some resources: the sequence of octets defined by a component of the URI is then used to represent a sequence of characters. A 'charset' defines this mapping, and there are many charsets in use across Internet protocols. For example, UTF-8 [UTF-8] defines a mapping from sequences of octets to sequences of characters in the repertoire of ISO 10646 ๐ŸŒˆ.

In the simplest case, the original character sequence contains only characters defined in US-ASCII, and the two levels of mapping are simple and easy to reverse. Each original character is represented as the octet for its US-ASCII code, and that octet is in turn represented either as the US-ASCII character itself or as the "%" escape sequence for that octet ๐Ÿ’–.

Things get trickier for original character sequences that contain non-ASCII characters ๐Ÿ™ˆ. Internet protocols that transmit octet sequences meant to represent character sequences are expected to provide some way of identifying the charset used, if there might be more than one [RFC2277]. But right now there's no provision in the generic URI syntax to do that identification. An individual URI scheme may require a single charset, define a default charset, or provide a way to indicate which charset is used ๐Ÿซถ.

A systematic treatment of character encoding within URIs is expected to be developed as a future modification of this specification ๐Ÿ”ฎ.

2.2. Reserved Characters ๐Ÿ‘‘

Lots of URIs include components that consist of, or are delimited by, certain special characters ๐Ÿ’…. These are called "reserved", because their use within a URI component is limited to their reserved purpose. If the data for a URI component would conflict with that reserved purpose, then the conflicting data must be escaped before the URI is formed ๐Ÿšซ.

reserved    = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" |
              "$" | ","

The "reserved" syntax class above refers to characters that are allowed within a URI but which may not be allowed within a particular component of the generic URI syntax. They're used as delimiters of the components described in Section 3 โœจ.

Reserved characters aren't reserved in every context ๐Ÿ™ƒ. The set of characters that are actually reserved within any given URI component is defined by that component. In general, a character is reserved if the semantics of the URI change when that character is replaced with its escaped US-ASCII encoding ๐Ÿ”ฅ.

2.3. Unreserved Characters ๐ŸŒท

Data characters that are allowed in a URI but don't have a reserved purpose are called unreserved ๐Ÿ“. These include upper and lower case letters, decimal digits, and a limited set of punctuation marks and symbols.

unreserved  = alphanum | mark

mark        = "-" | "_" | "." | "!" | "~" | "*" | "'" | "(" | ")"

Unreserved characters can be escaped without changing the semantics of the URI, but this should not be done unless the URI is being used in a context that doesn't allow the unescaped character to appear ๐Ÿ™…โ€โ™€๏ธ.

2.4. Escape Sequences ๐ŸŽ€

Data must be escaped if it doesn't have a representation using an unreserved character ๐Ÿ’–. That includes data that doesn't correspond to a printable character of the US-ASCII coded character set, and data that corresponds to any US-ASCII character that is disallowed, as explained below ๐Ÿ˜ค.

2.4.1. Escaped Encoding ๐Ÿง

An escaped octet is encoded as a character triplet, made up of the percent character "%" followed by the two hexadecimal digits that represent the octet code. For example, "%20" is the escaped encoding for the US-ASCII space character ๐ŸŒˆ.

escaped     = "%" hex hex
hex         = digit | "A" | "B" | "C" | "D" | "E" | "F" |
                      "a" | "b" | "c" | "d" | "e" | "f"

2.4.2. When to Escape and Unescape โœจ

okay so a URI is ALWAYS in its "escaped" form, bestie ๐Ÿ’… because escaping or unescaping a finished URI might literally change what it means ๐Ÿ˜ญ The only safe time to make escape encodings is when the URI is being built from its component parts. Each component can have its own set of reserved characters, so only the mechanism that generates or interprets that component can tell whether escaping a character will change its meaning. Same energy on the way back: you have to split a URI into its components BEFORE you can safely decode the escaped characters inside them ๐Ÿงฉ

Sometimes data that could've been written as an unreserved character shows up escaped anyway. For example, some of the unreserved "mark" characters get auto-escaped by certain systems ๐Ÿ™ˆ If a URI scheme has a canonicalization algorithm, then unreserved characters can be unescaped according to that algorithm. Like, %7e is sometimes used instead of ~ in an http URL path, but for an http URL those two are equivalent. no cap ๐Ÿซถ

Because the percent % character always has the reserved job of being the escape indicator, it has to be escaped as %25 if you want to use it as data inside a URI. Implementers, PLEASE be careful not to escape or unescape the same string more than once ๐Ÿ’€ Unescaping something that's already unescaped can make a percent data character look like an escaped character, and the reverse happens when you escape something that's already escaped. Chaos, periodt ๐ŸŒช๏ธ


2.4.3. Excluded US-ASCII Characters ๐Ÿฆ‹

Even though these characters are NOT allowed in the URI syntax, we're listing them here so you can see which US-ASCII characters got excluded and why. It's giving "know your enemies" ๐Ÿ˜ค

The control characters in the US-ASCII coded character set aren't used in a URI. Two reasons: they're non-printable, and some control mechanisms are likely to misinterpret them ๐Ÿ™…โ€โ™€๏ธ

control     = <US-ASCII coded characters 00-1F and 7F hexadecimal>

The space character is excluded because significant spaces can disappear, and insignificant spaces can sneak in, when URIs get transcribed, typeset, or run through word-processing programs ๐Ÿ“ Whitespace is also used to delimit URIs in lots of contexts, so yeah, it's a no from us ๐Ÿšซ

space       = <US-ASCII coded character 20 hexadecimal>

The angle brackets < and > and the double-quote (") are excluded because they're often used as delimiters around URIs in text documents and protocol fields ๐ŸŽ€ The character # is excluded because it separates a URI from a fragment identifier in URI references (Section 4). And the percent character % is excluded because it's used for encoding escaped characters. Main character energy, but make it a delimiter ๐Ÿ‘‘

delims      = "<" | ">" | "#" | "%" | <">

Other characters are excluded because gateways and other transport agents are known to sometimes modify them, or because they're used as delimiters. lowkey chaotic ๐ŸŒ€

unwise      = "{" | "}" | "|" | "\" | "^" | "[" | "]" | "`"

Data that corresponds to excluded characters has to be escaped to be properly represented inside a URI. Bestie, that's the whole rule ๐ŸŒธ


3. URI Syntactic Components ๐ŸŽ€

The URI syntax depends on the scheme ๐Ÿงš In general, absolute URIs are written like this:

<scheme>:<scheme-specific-part>

So an absolute URI has the name of the scheme being used (<scheme>), followed by a colon (:), and then a string (the <scheme-specific-part>) whose meaning depends on the scheme. It's a whole vibe ๐Ÿ’–

The URI syntax doesn't require the scheme-specific-part to have any general structure or set of semantics that all URIs share. HOWEVER, a subset of URIs do share a common syntax for showing hierarchical relationships within the namespace. This "generic URI" syntax is made up of four main components:

<scheme>://<authority><path>?<query>

Each one of those, except <scheme>, can be absent from a particular URI. For example, some URI schemes don't allow an <authority> component, and others don't use a <query> component ๐Ÿคทโ€โ™€๏ธ

absoluteURI   = scheme ":" ( hier_part | opaque_part )

URIs that are hierarchical in nature use the slash / character to separate their hierarchical components. For some file systems, a / (used to show the hierarchical structure of a URI) is the delimiter used to build a file name hierarchy, so the URI path can look a lot like a file pathname ๐Ÿ“‚ This does NOT imply that the resource is a file, or that the URI maps to an actual filesystem pathname. Not the same thing, babe ๐Ÿ™…โ€โ™€๏ธ

hier_part     = ( net_path | abs_path ) [ "?" query ]

net_path      = "//" authority [ abs_path ]

abs_path      = "/"  path_segments

URIs that don't use the slash / character to separate hierarchical components are considered opaque by the generic URI parser. Mysterious and iconic ๐Ÿ•ต๏ธโ€โ™€๏ธ

opaque_part   = uric_no_slash *uric

uric_no_slash = unreserved | escaped | ";" | "?" | ":" | "@" |
                "&" | "=" | "+" | "$" | ","

We use the term <path> to refer to both the <abs_path> and <opaque_part> constructs. They're mutually exclusive for any given URI and can be parsed as a single component, so we group them together ๐Ÿซถ


3.1. Scheme Component ๐ŸŒˆ

Just like there are tons of ways to access resources, there are a bunch of schemes for identifying them โœจ The URI syntax is a sequence of components separated by reserved characters, and the first component sets the semantics for the rest of the URI string. The first one is in charge, honestly ๐Ÿ‘‘

Scheme names are a sequence of characters that begin with a lower case letter, followed by any combo of lower case letters, digits, plus (+), period (.), or hyphen (-). For resiliency, programs that interpret URIs should treat upper case letters as equivalent to lower case in scheme names (for example, allowing "HTTP" as well as "http"). Be nice to the uppercase kids ๐Ÿฅน

scheme        = alpha *( alpha | digit | "+" | "-" | "." )

Relative URI references are different from absolute URIs because they don't start with a scheme name. Instead, the scheme gets inherited from the base URI, as described in Section 5.2 ๐Ÿฆ‹


3.2. Authority Component ๐Ÿ›๏ธ

A lot of URI schemes include a top hierarchical element for a naming authority, so the namespace defined by the rest of the URI is governed by that authority. The authority component is usually defined by an Internet-based server or a scheme-specific registry of naming authorities ๐Ÿ“‹

authority     = server | reg_name

The authority component is preceded by a double slash //, and it ends at the next slash /, question-mark ?, or the end of the URI. Inside the authority component, the characters ;, :, @, ?, and / are reserved ๐Ÿšง

An authority component isn't required for a URI scheme to use relative references. A base URI without an authority component means any relative reference will also be without an authority component. It's all connected, bestie ๐Ÿซถ

3.2.1. Registry-based Naming Authority ๐Ÿ“š

The structure of a registry-based naming authority is specific to the URI scheme, but it's still limited to the characters that are allowed in an authority component ๐Ÿ’…

reg_name      = 1*( unreserved | escaped | "$" | "," |
                    ";" | ":" | "@" | "&" | "=" | "+" )

3.2.2. Server-based Naming Authority ๐Ÿ–ฅ๏ธ

URL schemes that directly use an IP-based protocol to reach a specified server on the Internet use a common syntax for the server component of the URI's scheme-specific data:

<userinfo>@<host>:<port>

where <userinfo> can have a user name and, optionally, scheme-specific info about how to get authorization to access the server. The parts <userinfo>@ and :<port> can be left out ๐Ÿ™ˆ

server        = [ [ userinfo "@" ] hostport ]

If user information is present, it's followed by a commercial at-sign @ ๐Ÿ“ง

userinfo      = *( unreserved | escaped |
                   ";" | ":" | "&" | "=" | "+" | "$" | "," )

Some URL schemes use the format "user:password" in the userinfo field. This practice is NOT RECOMMENDED, because passing authentication info in clear text (like in a URI) has proven to be a security risk in almost every case where it's been used. Please don't do this, it's genuinely dangerous ๐Ÿ˜ญ๐Ÿšจ

Heads up: passing authentication info in clear text inside a URI has proven to be a security risk in almost every case where it's been used. Be careful out there, bestie ๐Ÿ’€

The host is a domain name of a network host, or its IPv4 address written as a set of four decimal digit groups separated by .. Literal IPv6 addresses are NOT supported, sorry not sorry ๐Ÿฅฒ

hostport      = host [ ":" port ]
host          = hostname | IPv4address
hostname      = *( domainlabel "." ) toplabel [ "." ]
domainlabel   = alphanum | alphanum *( alphanum | "-" ) alphanum
toplabel      = alpha | alpha *( alphanum | "-" ) alphanum
IPv4address   = 1*digit "." 1*digit "." 1*digit "." 1*digit
port          = *digit

Hostnames take the form described in Section 3 of [RFC1034] and Section 2.1 of [RFC1123]: a sequence of domain labels separated by ., with each domain label starting and ending with an alphanumeric character and possibly also containing - characters. The rightmost domain label of a fully qualified domain name will never start with a digit, which is how domain names are told apart from IPv4 addresses ๐Ÿ” It may be followed by a single . if it's necessary to tell the complete domain name apart from any local domain. To actually be "Uniform" as a resource locator, a URL hostname should be a fully qualified domain name. In practice, though, the host component may be a local domain literal ๐Ÿ 

Note: A suitable representation for including a literal IPv6 address as the host part of a URL is desired, but hasn't yet been determined or implemented in practice. IPv6, we're still waiting on you ๐Ÿ‘€

The port is the network port number for the server. Most schemes designate protocols that have a default port number. Another port number may optionally be supplied, in decimal, separated from the host by a colon. If the port is omitted, the default port number is assumed ๐Ÿ”Œ


3.3. Path Component ๐Ÿ›ค๏ธ

The path component holds data, specific to the authority (or to the scheme if there's no authority component), that identifies the resource within the scope of that scheme and authority. It's giving GPS for resources ๐Ÿ—บ๏ธ

path          = [ abs_path | opaque_part ]

path_segments = segment *( "/" segment )
segment       = *pchar *( ";" param )
param         = *pchar

pchar         = unreserved | escaped |
                ":" | "@" | "&" | "=" | "+" | "$" | ","

The path may be made of a sequence of path segments separated by a single slash / character. Inside a path segment, the characters /, ;, =, and ? are reserved. Each path segment may include a sequence of parameters, marked by the semicolon ; character. The parameters aren't significant to the parsing of relative references, so you can relax about them ๐ŸŒธ


3.4. Query Component ๐Ÿ”

The query component is a string of information that's meant to be interpreted by the resource ๐Ÿ’œ

query         = *uric

Inside a query component, the characters ;, /, ?, :, @, &, =, +, ,, and $ are reserved ๐Ÿซง

4. URI References โœจ

okay bestie, so "URI-reference" is just the everyday way of saying a resource identifier ๐Ÿ’…. A URI reference can be absolute or relative, and it can also have a fragment identifier tacked on the end ๐ŸŽ€. BUT here's the tea: "the URI" that comes out of a reference only includes the absolute URI, with the fragment chopped off and any relative bit resolved into its full absolute form ๐Ÿฆ‹. You could talk about syntax and meaning using just the absolute result, but most real usage is in general URI references, so you literally can't get the URI without parsing the fragment and resolving the relative form too ๐Ÿ˜ญ.

URI-reference = [ absoluteURI | relativeURI ] [ "#" fragment ]

the relative URI syntax is basically a shortened version of the absolute one ๐ŸŒธ. some prefix of the URI goes missing, and the path pieces "." and ".." only get their special meaning when you're interpreting a relative path ๐Ÿงš. the relative URI syntax lives in Section 5, so keep scrolling bestie ๐Ÿ‘‘.

4.1. Fragment Identifier

when you use a URI reference to retrieve the resource it points to, the optional fragment identifier shows up after a crosshatch ("#") character ๐Ÿฆ‹. it holds extra reference info that the user agent interprets after the retrieval has successfully finished โœจ. so ngl, it's not technically part of a URI, but it's almost always used together with one ๐Ÿซถ.

fragment      = *uric

what a fragment means depends on the data you got back from the retrieval, no matter what kind of URI you used ๐Ÿ’œ. that means the format and interpretation of fragment identifiers depend on the media type [RFC2046] of the retrieval result ๐ŸŒˆ. the character restrictions from Section 2 for URI also apply to the fragment in a URI-reference ๐Ÿ’…. individual media types can add their own restrictions or structure inside the fragment, so they can name different kinds of "partial views" in that media type ๐ŸŽ€.

a fragment identifier only makes sense when the URI reference is meant for retrieval AND the result is a document where that fragment is consistently defined ๐Ÿ˜ญ๐ŸŒธ.

4.2. Same-document References

a URI reference that doesn't contain a URI is a reference to the current document, lowkey the simplest vibe ever ๐Ÿ“. so an empty URI reference inside a document means the start of that document, and a reference with only a fragment identifier means that fragment inside the same document โœจ. traversing one of these should not result in an additional retrieval action ๐Ÿ™ˆ. BUT if the URI reference shows up somewhere that's always meant to make a brand new request, like HTML's FORM element, then an empty URI reference stands for the base URI of the current document, and it should be replaced by that URI when it gets turned into a request ๐Ÿ’–.

4.3. Parsing a URI Reference

a URI reference is usually parsed by the four main components plus the fragment identifier, in order ๐Ÿงš. that tells you which components are present and whether the reference is relative or absolute ๐Ÿ‘‘. then each component gets parsed for its subparts and, if it isn't opaque, checked for validity ๐Ÿ”ฅ.

although the BNF says what's allowed in each component, it's kinda ambiguous when it comes to telling an authority component apart from a path component that starts with two slash characters ๐Ÿ˜ญ. so the greedy algorithm handles the disambiguation: the left-most matching rule soaks up as much of the URI reference string as it can match ๐Ÿฆ‹. in other words, the authority component wins ๐Ÿ’….

readers who love regular expressions should check out Appendix B for a concrete parsing example and test oracle ๐Ÿค“๐Ÿ’œ.


5. Relative URI References

okay so it's super common for a whole group or "tree" of documents to be built for one purpose, and the vast majority of URI in those documents point to resources inside the tree rather than outside it ๐ŸŒณ. same vibe for documents at a particular site: they're way more likely to refer to other resources on that site than to resources at remote sites ๐Ÿกโœจ.

relative addressing lets document trees stay partly independent of their location and access scheme ๐Ÿฆ‹. like, a single set of hypertext documents can be accessed and traversed through each of the "file", "http", and "ftp" schemes at the same time, as long as the documents refer to each other with relative URI ๐ŸŒˆ. and the whole tree can be moved around without changing any of the relative references ๐ŸŽ€. experience within the WWW has shown that being able to do relative referencing is necessary for the long-term usability of embedded URI ๐Ÿ˜ญ๐Ÿ’….

the syntax for relative URI takes advantage of the <hier_part> syntax of <absoluteURI> (Section 3), so it can express a reference that's relative to the namespace of another hierarchical URI ๐Ÿงš.

relativeURI   = ( net_path | abs_path | rel_path ) [ "?" query ]

a relative reference that starts with two slash characters is called a network-path reference, as defined by <net_path> in Section 3 ๐Ÿซถ. these are rarely used, bestie ๐Ÿ™ˆ.

a relative reference that starts with a single slash character is called an absolute-path reference, as defined by <abs_path> in Section 3 ๐ŸŒธ.

a relative reference that doesn't begin with a scheme name or a slash character is called a relative-path reference ๐Ÿ’œ.

rel_path      = rel_segment [ abs_path ]

rel_segment   = 1*( unreserved | escaped |
                    ";" | "@" | "&" | "=" | "+" | "$" | "," )

inside a relative-path reference, the complete path segments "." and ".." have special meanings: "the current hierarchy level" and "the level above this hierarchy level" ๐Ÿฆ‹. this is super similar to how Unix-based filesystems use them for directory levels, but here they only count as special when you're resolving a relative-path reference to its absolute form (Section 5.2) ๐ŸŽ€.

โš ๏ธ authors, listen up: a path segment containing a colon character can't be the first segment of a relative URI path (for example, "this:that"), because it would get mistaken for a scheme name ๐Ÿ˜ญ๐Ÿ’€.

so you have to put other segments in front of it (like "./this:that") if you want to reference it as a relative path ๐Ÿงšโœจ.

it's not necessary for every URI within a given scheme to follow the <hier_part> syntax ๐ŸŒˆ. the hierarchical properties of that syntax only matter when relative URI are used within a particular document ๐Ÿ’…. documents can only use relative URI when their base URI fits the <hier_part> syntax, and it's assumed that any document with a relative reference also has a base URI that follows the syntax ๐Ÿซถ. in other words, relative URI can't be used inside a document with an unsuitable base URI ๐Ÿ™ˆ.

some URI schemes don't allow a hierarchical syntax matching <hier_part>, so they can't use relative references at all ๐Ÿ˜ญ๐ŸŒธ.

5.1. Establishing a Base URI

the term "relative URI" implies there's some absolute "base URI" that the relative reference gets applied against ๐Ÿ’–. honestly the base URI is needed to define the semantics of any relative URI reference, because without it, a relative reference is meaningless ๐Ÿ”ฅ. so for relative URI to be usable within a document, the parser has to know that document's base URI ๐Ÿ‘‘.

there are four ways to establish the base URI of a document, listed below in order of precedence ๐ŸŽ€. think of the precedence like layers, where the innermost defined base URI has the highest precedence ๐ŸŒˆ. here's the visual:

  .----------------------------------------------------------.
  |  .----------------------------------------------------.  |
  |  |  .----------------------------------------------.  |  |
  |  |  |  .----------------------------------------.  |  |  |
  |  |  |  |  .----------------------------------.  |  |  |  |
  |  |  |  |  |       <relative_reference>       |  |  |  |  |
  |  |  |  |  `----------------------------------'  |  |  |  |
  |  |  |  | (5.1.1) Base URI embedded in the       |  |  |  |
  |  |  |  |         document's content             |  |  |  |
  |  |  |  `----------------------------------------'  |  |  |
  |  |  | (5.1.2) Base URI of the encapsulating entity |  |  |
  |  |  |         (message, document, or none).        |  |  |
  |  |  `----------------------------------------------'  |  |
  |  | (5.1.3) URI used to retrieve the entity            |  |
  |  `----------------------------------------------------'  |
  | (5.1.4) Default Base URI is application-dependent        |
  `----------------------------------------------------------'

5.1.1. Base URI within Document Content

some document media types can have the base URI embedded right inside the content, so a parser can grab it easily ๐Ÿงš. this is handy for descriptive documents like tables of content, which might get sent to people through protocols other than their usual retrieval context (like E-Mail or USENET news) ๐Ÿ’Œ.

it's beyond the scope of this document to spell out how the base URI gets embedded for each media type ๐Ÿ™ˆ. it's assumed that user agents handling those media types can get the right syntax from that media type's specification ๐Ÿ’…. an example of embedding the base URI in the Hypertext Markup Language (HTML) [RFC1866] is provided in Appendix D ๐ŸŒธ.

a mechanism for embedding the base URI within MIME container types (like the message and multipart types) is defined by MHTML [RFC2110] ๐Ÿฆ‹. protocols that don't use the MIME message header syntax, but do allow some form of tagged metainformation inside messages, can define their own syntax for putting the base URI into a message ๐Ÿซถโœจ.

5.1.2. Base URI from the Encapsulating Entity

if no base URI is embedded, the base URI of a document is defined by the document's retrieval context ๐ŸŽ€. for a document enclosed inside another entity (like a message or another document), that retrieval context is the enclosing entity ๐ŸŒˆ. so the default base URI of the document is the base URI of the entity it's encapsulated in ๐Ÿ’œ.

5.1.3. Base URI from the Retrieval URI

if no base URI is embedded AND the document isn't encapsulated inside some other entity (like the top level of a composite entity), then, if a URI was used to retrieve the base document, that URI shall be considered the base URI ๐Ÿ”ฅ. note: if the retrieval was the result of a redirected request, the last URI used (the one that actually resulted in retrieving the document) is the base URI ๐Ÿ‘‘๐Ÿ’–.

5.1.4. Default Base URI ๐ŸŒธ

okay so if none of the conditions in Sections 5.1.1--5.1.3 apply, then the base URI is defined by the context of the application ๐Ÿ’…. Since that definition is necessarily application-dependent, failing to define the base URI using one of the other methods may result in the same content being interpreted differently by different types of application. bestie this is the drama ๐Ÿ˜ญ

It is the responsibility of the distributor(s) of a document containing relative URI to ensure that the base URI for that document can be established. It must be emphasized that relative URI cannot be used reliably in situations where the document's base URI is not well-defined ๐Ÿซถ so please, distributors, give your docs a clear base URI!!

5.2. Resolving Relative References to Absolute Form โœจ

this section gives an example algorithm for resolving URI references that might be relative to a given base URI. it's giving glow-up energy for URIs ๐Ÿฆ‹

The base URI is established according to the rules of Section 5.1 and parsed into the four main components as described in Section 3. Note that only the scheme component is required to be present in the base URI; the other components may be empty or undefined. A component is undefined if its preceding separator does not appear in the URI reference; the path component is never undefined, though it may be empty. The base URI's query component is not used by the resolution algorithm and may be discarded ๐ŸŽ€

For each URI reference, the following steps are performed in order:

  1. The URI reference is parsed into the potential four components and fragment identifier, as described in Section 4.3.
  2. If the path component is empty and the scheme, authority, and query components are undefined, then it is a reference to the current document and we are done. Otherwise, the reference URI's query and fragment components are defined as found (or not found) within the URI reference and not inherited from the base URI.
  3. If the scheme component is defined, indicating that the reference starts with a scheme name, then the reference is interpreted as an absolute URI and we are done. Otherwise, the reference URI's scheme is inherited from the base URI's scheme component.

Due to a loophole in prior specifications [RFC1630], some parsers allow the scheme name to be present in a relative URI if it is the same as the base URI scheme. Unfortunately, this can conflict with the correct parsing of non-hierarchical URI. For backwards compatibility, an implementation may work around such references by removing the scheme if it matches that of the base URI and the scheme is known to always use the <hier_part> syntax. The parser can then continue with the steps below for the remainder of the reference components. Validating parsers should mark such a misformed relative reference as an error ๐Ÿ™ˆ that's a lot of loophole energy, not it!!

  1. If the authority component is defined, then the reference is a network-path and we skip to step 7. Otherwise, the reference URI's authority is inherited from the base URI's authority component, which will also be undefined if the URI scheme does not use an authority component.
  2. If the path component begins with a slash character ("/"), then the reference is an absolute-path and we skip to step 7.
  3. If this step is reached, then we are resolving a relative-path reference. The relative path needs to be merged with the base URI's path. Although there are many ways to do this, we will describe a simple method using a separate string buffer ๐Ÿงš

a) All but the last segment of the base URI's path component is copied to the buffer. In other words, any characters after the last (right-most) slash character, if any, are excluded.

b) The reference's path component is appended to the buffer string.

c) All occurrences of "./", where "." is a complete path segment, are removed from the buffer string.

d) If the buffer string ends with "." as a complete path segment, that "." is removed.

e) All occurrences of "<segment>/../", where <segment> is a complete path segment not equal to "..", are removed from the buffer string. Removal of these path segments is performed iteratively, removing the leftmost matching pattern on each iteration, until no matching pattern remains.

f) If the buffer string ends with "<segment>/..", where <segment> is a complete path segment not equal to "..", that "<segment>/.." is removed.

g) If the resulting buffer string still begins with one or more complete path segments of "..", then the reference is considered to be in error. Implementations may handle this error by retaining these components in the resolved path (i.e., treating them as part of the final URI), by removing them from the resolved path (i.e., discarding relative levels above the root), or by avoiding traversal of the reference.

h) The remaining buffer string is the reference URI's new path component.

  1. The resulting URI components, including any inherited from the base URI, are recombined to give the absolute form of the URI reference. Using pseudocode, this would be
         result = ""

         if scheme is defined then
             append scheme to result
             append ":" to result

         if authority is defined then
             append "//" to result
             append authority to result

         append path to result

         if query is defined then
             append "?" to result
             append query to result

         if fragment is defined then
             append "#" to result
             append fragment to result

         return result

Note that we must be careful to preserve the distinction between a component that is undefined, meaning that its separator was not present in the reference, and a component that is empty, meaning that the separator was present and was immediately followed by the next component separator or the end of the reference. this one is SO important, don't mix them up ๐Ÿ’–

The above algorithm is intended to provide an example by which the output of implementations can be tested -- implementation of the algorithm itself is not required. For example, some systems may find it more efficient to implement step 6 as a pair of segment stacks being merged, rather than as a series of string pattern replacements ๐ŸŒˆ so you do you, as long as the output matches!

Note: Some WWW client applications will fail to separate the reference's query component from its path component before merging the base and reference paths in step 6 above. This may result in a loss of information if the query component contains the strings "/../" or "/./". yikes, that's a big oops ๐Ÿ’€

Resolution examples are provided in Appendix C. ๐ŸŽ€


6. URI Normalization and Equivalence โœจ

in lots of cases, different URI strings can actually identify the identical resource ๐Ÿฆ‹ for example, the host names used in URL are actually case insensitive, and the URL <http://www.XEROX.com> is equivalent to <http://www.xerox.com>. in general, the rules for equivalence and definition of a normal form, if any, are scheme dependent. When a scheme uses elements of the common syntax, it will also use the common syntax equivalence rules, namely that the scheme and hostname are case insensitive and a URL with an explicit ":port", where the port is the default for the scheme, is equivalent to one where the port is elided. so the same vibe, different spelling, periodt ๐Ÿ’…


7. Security Considerations ๐Ÿ”ฅ

a URI does not in itself pose a security threat ๐Ÿ’œ but users should beware that there is no general guarantee that a URL, which at one time located a given resource, will continue to do so. Nor is there any guarantee that a URL will not locate a different resource at some later point in time, due to the lack of any constraint on how a given authority apportions its namespace. Such a guarantee can only be obtained from the person(s) controlling that namespace and the resource in question. A specific URI scheme may include additional semantics, such as name persistence, if those semantics are required of all naming authorities for that scheme.

it is sometimes possible to construct a URL such that an attempt to perform a seemingly harmless, idempotent operation, such as the retrieval of an entity associated with the resource, will in fact cause a possibly damaging remote operation to occur. The unsafe URL is typically constructed by specifying a port number other than that reserved for the network protocol in question. The client unwittingly contacts a site that is in fact running a different protocol. The content of the URL contains instructions that, when interpreted according to this other protocol, cause an unexpected operation. An example has been the use of a gopher URL to cause an unintended or impersonating message to be sent via a SMTP server ๐Ÿ˜ฑ this is the plot twist nobody asked for!!

Caution should be used when using any URL that specifies a port number other than the default for the protocol, especially when it is a number within the reserved space. ๐Ÿšจ

Care should be taken when a URL contains escaped delimiters for a given protocol (for example, CR and LF characters for telnet protocols) that these are not unescaped before transmission. This might violate the protocol, but avoids the potential for such characters to be used to simulate an extra operation or parameter in that protocol, which might lead to an unexpected and possibly harmful remote operation to be performed ๐Ÿ›ก๏ธ keep those escaped delimiters escaped, bestie.

It is clearly unwise to use a URL that contains a password which is intended to be secret. In particular, the use of a password within the 'userinfo' component of a URL is strongly disrecommended except in those rare cases where the 'password' parameter is intended to be public. ๐Ÿ™ˆ do NOT put secrets in the URL, I'm begging you ๐Ÿ˜ญ


8. Acknowledgements ๐Ÿซถ

This document was derived from RFC 1738 [RFC1738] and RFC 1808 [RFC1808]; the acknowledgements in those specifications still apply. In addition, contributions by Gisle Aas, Martin Beet, Martin Duerst, Jim Gettys, Martijn Koster, Dave Kristol, Daniel LaLiberte, Foteos Macrides, James Marshall, Ryan Moats, Keith Moore, and Lauren Wood are gratefully acknowledged. big thank you to all the legends who made this happen ๐Ÿ‘‘๐Ÿ’–

9. References ๐Ÿ“šโœจ

okay bestie, the references section is where the receipts live ๐Ÿงพ๐Ÿ’… each one is a whole doc that the spec leans on, so I'm keeping every title, number, and date exactly as written:

  • [RFC2277] Alvestrand, H., "IETF Policy on Character Sets and Languages", BCP 18, RFC 2277, January 1998. ๐ŸŒ
  • [RFC1630] Berners-Lee, T., "Universal Resource Identifiers in WWW: A Unifying Syntax for the Expression of Names and Addresses of Objects on the Network as used in the World-Wide Web", RFC 1630, June 1994. ๐Ÿ•ธ๏ธ
  • [RFC1738] Berners-Lee, T., Masinter, L., and M. McCahill, Editors, "Uniform Resource Locators (URL)", RFC 1738, December 1994. ๐Ÿ”—
  • [RFC1866] Berners-Lee T., and D. Connolly, "HyperText Markup Language Specification -- 2.0", RFC 1866, November 1995. ๐Ÿ“„
  • [RFC1123] Braden, R., Editor, "Requirements for Internet Hosts -- Application and Support", STD 3, RFC 1123, October 1989. ๐Ÿ–ฅ๏ธ
  • [RFC822] Crocker, D., "Standard for the Format of ARPA Internet Text Messages", STD 11, RFC 822, August 1982. ๐Ÿ’Œ
  • [RFC1808] Fielding, R., "Relative Uniform Resource Locators", RFC 1808, June 1995. ๐Ÿงญ
  • [RFC2046] Freed, N., and N. Borenstein, "Multipurpose Internet Mail Extensions (MIME) Part Two: Media Types", RFC 2046, November 1996. ๐ŸŽ€
  • [RFC1736] Kunze, J., "Functional Recommendations for Internet Resource Locators", RFC 1736, February 1995. ๐ŸŒธ
  • [RFC2141] Moats, R., "URN Syntax", RFC 2141, May 1997. ๐Ÿท๏ธ
  • [RFC1034] Mockapetris, P., "Domain Names - Concepts and Facilities", STD 13, RFC 1034, November 1987. ๐Ÿ—บ๏ธ
  • [RFC2110] Palme, J., and A. Hopmann, "MIME E-mail Encapsulation of Aggregate Documents, such as HTML (MHTML)", RFC 2110, March 1997. ๐Ÿฆ‹
  • [RFC1737] Sollins, K., and L. Masinter, "Functional Requirements for Uniform Resource Names", RFC 1737, December 1994. ๐Ÿงš
  • [ASCII] US-ASCII. "Coded Character Set -- 7-bit American Standard Code for Information Interchange", ANSI X3.4-1986. ๐Ÿ”ค
  • [UTF-8] Yergeau, F., "UTF-8, a transformation format of ISO 10646", RFC 2279, January 1998. ๐ŸŒˆ

10. Authors' Addresses ๐Ÿ’œ

these are the people who put this whole thing together, so let's give them their flowers ๐ŸŒท

Tim Berners-Lee
World Wide Web Consortium
MIT Laboratory for Computer Science, NE43-356
545 Technology Square
Cambridge, MA 02139

Fax: +1(617)258-8682
EMail: timbl@w3.org


Roy T. Fielding
Department of Information and Computer Science
University of California, Irvine
Irvine, CA  92697-3425

Fax: +1(949)824-1715
EMail: fielding@ics.uci.edu


Larry Masinter
Xerox PARC
3333 Coyote Hill Road
Palo Alto, CA 94034

Fax: +1(415)812-4333
EMail: masinter@parc.xerox.com

A. Collected BNF for URI ๐Ÿงฉ

this is the whole grammar in one place, the ultimate cheat sheet ๐Ÿ“‹โœจ copied exactly so nothing gets lost in translation:

      URI-reference = [ absoluteURI | relativeURI ] [ "#" fragment ]
      absoluteURI   = scheme ":" ( hier_part | opaque_part )
      relativeURI   = ( net_path | abs_path | rel_path ) [ "?" query ]

      hier_part     = ( net_path | abs_path ) [ "?" query ]
      opaque_part   = uric_no_slash *uric

      uric_no_slash = unreserved | escaped | ";" | "?" | ":" | "@" |
                      "&" | "=" | "+" | "$" | ","

      net_path      = "//" authority [ abs_path ]
      abs_path      = "/"  path_segments
      rel_path      = rel_segment [ abs_path ]

      rel_segment   = 1*( unreserved | escaped |
                          ";" | "@" | "&" | "=" | "+" | "$" | "," )

      scheme        = alpha *( alpha | digit | "+" | "-" | "." )

      authority     = server | reg_name

      reg_name      = 1*( unreserved | escaped | "$" | "," |
                          ";" | ":" | "@" | "&" | "=" | "+" )

      server        = [ [ userinfo "@" ] hostport ]
      userinfo      = *( unreserved | escaped |
                         ";" | ":" | "&" | "=" | "+" | "$" | "," )

      hostport      = host [ ":" port ]
      host          = hostname | IPv4address
      hostname      = *( domainlabel "." ) toplabel [ "." ]
      domainlabel   = alphanum | alphanum *( alphanum | "-" ) alphanum
      toplabel      = alpha | alpha *( alphanum | "-" ) alphanum
      IPv4address   = 1*digit "." 1*digit "." 1*digit "." 1*digit
      port          = *digit

      path          = [ abs_path | opaque_part ]
      path_segments = segment *( "/" segment )
      segment       = *pchar *( ";" param )
      param         = *pchar
      pchar         = unreserved | escaped |
                      ":" | "@" | "&" | "=" | "+" | "$" | ","

      query         = *uric

      fragment      = *uric
      uric          = reserved | unreserved | escaped
      reserved      = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" |
                      "$" | ","
      unreserved    = alphanum | mark
      mark          = "-" | "_" | "." | "!" | "~" | "*" | "'" |
                      "(" | ")"

      escaped       = "%" hex hex
      hex           = digit | "A" | "B" | "C" | "D" | "E" | "F" |
                              "a" | "b" | "c" | "d" | "e" | "f"

      alphanum      = alpha | digit
      alpha         = lowalpha | upalpha

      lowalpha = "a" | "b" | "c" | "d" | "e" | "f" | "g" | "h" | "i" |
                 "j" | "k" | "l" | "m" | "n" | "o" | "p" | "q" | "r" |
                 "s" | "t" | "u" | "v" | "w" | "x" | "y" | "z"
      upalpha  = "A" | "B" | "C" | "D" | "E" | "F" | "G" | "H" | "I" |
                 "J" | "K" | "L" | "M" | "N" | "O" | "P" | "Q" | "R" |
                 "S" | "T" | "U" | "V" | "W" | "X" | "Y" | "Z"
      digit    = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" |
                 "8" | "9"

B. Parsing a URI Reference with a Regular Expression ๐Ÿ”

okay so the generic URI syntax alone isn't enough to untangle some URI forms ๐Ÿฅด but the "greedy algorithm" from Section 4.3 works exactly like POSIX regular expressions do, so using a regex to split a URI reference into its four components plus fragment is totally natural and super common ๐Ÿ’–

here's the regex that breaks a URI reference down into its parts:

   ^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?
    12            3  4          5       6  7        8 9

the numbers on the second line are just there to help you read it ๐Ÿค“ they mark the reference point for each subexpression (aka each pair of parentheses). we call the value matched by subexpression <n> "$<n>". for example, when you match the regex against this:

   http://www.ics.uci.edu/pub/ietf/uri/#Related

you get these subexpression matches:

   $1 = http:
   $2 = http
   $3 = //www.ics.uci.edu
   $4 = www.ics.uci.edu
   $5 = /pub/ietf/uri/
   $6 = <undefined>
   $7 = <undefined>
   $8 = #Related
   $9 = Related

where <undefined> means the component isn't there at all, like the query in this example ๐Ÿซ  so the four components and fragment come out like this:

   scheme    = $2
   authority = $4
   path      = $5
   query     = $7
   fragment  = $9

and going the other direction ๐Ÿ”„ you can rebuild a URI reference from its components using the algorithm in step 7 of Section 5.2. โœจ


C. Examples of Resolving Relative URI References ๐Ÿ—บ๏ธ๐Ÿ’…

say your base is a hot little object with a well-defined base URI of:

   http://a/b/c/d;p?q

here's how relative URIs resolve against it. this is the main character moment ๐Ÿ‘‘

C.1. Normal Examples

      g:h           =  g:h
      g             =  http://a/b/c/g
      ./g           =  http://a/b/c/g
      g/            =  http://a/b/c/g/
      /g            =  http://a/g
      //g           =  http://g
      ?y            =  http://a/b/c/?y
      g?y           =  http://a/b/c/g?y
      #s            =  (current document)#s
      g#s           =  http://a/b/c/g#s
      g?y#s         =  http://a/b/c/g?y#s
      ;x            =  http://a/b/c/;x
      g;x           =  http://a/b/c/g;x
      g;x?y#s       =  http://a/b/c/g;x?y#s
      .             =  http://a/b/c/
      ./            =  http://a/b/c/
      ..            =  http://a/b/
      ../           =  http://a/b/
      ../g          =  http://a/b/g
      ../..         =  http://a/
      ../../        =  http://a/
      ../../g       =  http://a/g

C.2. Abnormal Examples

these weird ones probably won't show up in normal life ๐Ÿ™ˆ but every URI parser should still be able to resolve them the same way, consistently!! same base as before.

an empty reference points to the start of the current document ๐Ÿซง:

      <>            =  (current document)

parsers need to be extra careful when there are more ".." segments in the relative path than there are levels in the base URI's path ๐Ÿ˜ฌ also, ".." can never change the authority part of a URI, so it's not a sneaky way to jump to another host ๐Ÿšซ

      ../../../g    =  http://a/../g
      ../../../../g =  http://a/../../g
in practice, some implementations strip leading "." and ".." bits after doing the relative calculation. their thinking is that fixing obvious author mistakes beats letting the request fail ๐Ÿซถ so those two references above end up as "http://a/g" in some implementations.

also, parsers can't treat "." and ".." as special unless they're complete path segments ๐Ÿ™…โ€โ™€๏ธ

      /./g          =  http://a/./g
      /../g         =  http://a/../g
      g.            =  http://a/b/c/g.
      .g            =  http://a/b/c/.g
      g..           =  http://a/b/c/g..
      ..g           =  http://a/b/c/..g

then there are the extra-messy cases, where the relative URI has unnecessary or nonsense "." and ".." segments ๐ŸŒ€

      ./../g        =  http://a/b/g
      ./g/.         =  http://a/b/c/g/
      g/./h         =  http://a/b/c/g/h
      g/../h        =  http://a/b/c/h
      g;x=1/./y     =  http://a/b/c/g;x=1/y
      g;x=1/../y    =  http://a/b/c/y

every client strips the query off the base URI before resolving a relative URI, fr fr ๐Ÿ’ฏ but some apps forget to split the reference's query and/or fragment off from the relative path before they glue it onto the base path ๐Ÿ˜ญ that bug is rarely noticed, since fragments almost never have a "/" in them and queries usually aren't used in relative references anyway ๐ŸŒธ

      g?y/./x       =  http://a/b/c/g?y/./x
      g?y/../x      =  http://a/b/c/g?y/../x
      g#s/./x       =  http://a/b/c/g#s/./x
      g#s/../x      =  http://a/b/c/g#s/../x

finally, some parsers let a relative URI include the scheme name if it matches the base URI's scheme ๐Ÿคจ this is seen as a loophole in earlier partial URI specs [RFC1630], so it's best to avoid it ๐Ÿ™…โ€โ™€๏ธ

      http:g        =  http:g           ; for validating parsers
                    |  http://a/b/c/g   ; for backwards compatibility

D. Embedding the Base URI in HTML documents โœจ

okay so this one is super useful ๐ŸŽ€ Sometimes a document carries its own base URI right inside its content, and this appendix shows how HTML [RFC1866] documents can do that. Just so we're clear, this is a descriptive example and NOT part of the URI spec itself ๐Ÿ’…

HTML has a special element called "BASE" ๐Ÿงš When it shows up in the "HEAD" part of a document, it tells the parser to use the BASE element's "HREF" attribute as the base URI for resolving any relative URI. The "HREF" attribute must be an absolute URI, no shortcuts ๐Ÿ™… Also, in HTML, element and attribute names are case-insensitive ๐Ÿฆ‹ Here's a cute example:

<!doctype html public "-//IETF//DTD HTML//EN">
<HTML><HEAD>
<TITLE>An example HTML document</TITLE>
<BASE href="http://www.ics.uci.edu/Test/a/b/c">
</HEAD><BODY>
... <A href="../x">a hypertext anchor</A> ...
</BODY></HTML>

A parser reading that example should interpret the relative URI "../x" as representing the absolute URI

<http://www.ics.uci.edu/Test/a/x>

no matter where the example document was obtained ๐Ÿซถ


E. Recommendations for Delimiting URI in Context ๐ŸŒˆ

okay this is such a real problem bestie ๐Ÿ˜ญ URI often get sent through formats that don't give any clear context for reading them. Think plain text in emails, USENET news posts, and, most importantly, stuff printed on paper. So it's really important to be able to separate the URI from the rest of the text, especially from punctuation that could get mistaken for part of the URI ๐Ÿ’€

In practice people wrap URI in lots of different ways, but usually it's double-quotes "http://test.com/", angle brackets <http://test.com/>, or just plain whitespace:

                             http://test.com/

These wrappers are NOT part of the URI itself โœจ

If a fragment identifier goes with a URI reference, the fragment should go inside the brackets too, separated from the URI by a "#" character ๐Ÿฆ‹

Sometimes you need extra whitespace (spaces, linebreaks, tabs, etc.) to break a long URI across lines. That whitespace should be ignored when you pull the URI out ๐Ÿ“

No whitespace should be introduced after a hyphen ("-") character. Some typesetters and printers may (erroneously) add a hyphen at the end of a line when they break it, so if a URI has a line break right after a hyphen, the interpreter should ignore all unescaped whitespace around that break, and should be aware that the hyphen may or may not actually be part of the URI ๐Ÿ™ˆ

Using <> angle brackets around each URI is especially recommended as a delimiting style for URI that contain whitespace ๐Ÿ’œ

The prefix "URL:" (with or without a trailing space) was recommended as a way to help distinguish a URL from other bracketed designators, although this isn't common in practice ๐Ÿคทโ€โ™€๏ธ

For robustness, software that accepts user-typed URI should try to recognize and strip both delimiters and embedded whitespace ๐Ÿ’–

For example, this text:

Yes, Jim, I found it under "http://www.w3.org/Addressing/",
but you can probably pick it up from <ftp://ds.internic.
net/rfc/>.  Note the warning in <http://www.ics.uci.edu/pub/
ietf/uri/historical.html#WARNING>.

contains these URI references:

http://www.w3.org/Addressing/
ftp://ds.internic.net/rfc/
http://www.ics.uci.edu/pub/ietf/uri/historical.html#WARNING

F. Abbreviated URLs ๐Ÿ“บ

The URL syntax was designed to unambiguously reference network resources and to be extensible through the URL scheme. But as URL identification and usage became commonplace, traditional media (TV, radio, newspapers, billboards, etc.) started using abbreviated URL references more and more. These are references made up of only the authority and path portions of the identified resource, like:

www.w3.org/Addressing/

or just the DNS hostname on its own ๐Ÿงš These are mostly meant for humans to read rather than machines, on the assumption that context-based heuristics are enough to fill in the rest of the URL. For example, most hostnames starting with "www" probably have a URL prefix of "http://". There's no standard set of heuristics for figuring out abbreviated URL references, but lots of client implementations let users type them in and resolve them heuristically. Keep in mind that these heuristics may change over time, especially when new URL schemes are introduced ๐Ÿ’…

Here's the catch: an abbreviated URL has the same syntax as a relative URL path, so abbreviated URL references can't be used anywhere relative URLs are expected. That means they're limited to places with no defined base URL, like dialog boxes and off-line advertisements ๐Ÿ˜ญ


G. Summary of Non-editorial Changes ๐Ÿ“

G.1. Additions

okay here's what's new ๐ŸŒธ

  • Section 4 (URI References) was added to clear up the confusion about "what is a URI" and how to describe fragment identifiers, since they aren't part of the URI but are part of the URI syntax and parsing concerns. It also gives a reference definition for other IETF specifications (HTML, HTTP, etc.) that used to try redefining the URI syntax to account for fragment identifiers in URI references.
  • Section 2.4 was rewritten to clear up a number of misinterpretations and to leave room for fully internationalized URI.
  • Appendix F on abbreviated URLs was added to describe the shortened references you often see in TV and magazine ads, and to explain why they aren't used in other contexts.

G.2. Modifications from both RFC 1738 and RFC 1808

This section changed to URI syntax instead of just URL ๐ŸŽ€

Confusion about the terms "character encoding", the URI "character set", and escaping characters with %<hex><hex> equivalents has (hopefully) been reduced. A lot of the BNF rule names for the character sets were renamed so they better describe their purpose and cover all "characters" instead of just US-ASCII octets. Unless noted here, these changes don't affect the URI syntax โœจ

RFC 1738 and RFC 1808 both talk about the "reserved" set of characters as if URI-interpreting software was limited to one set of characters with a reserved purpose (meaning something other than the data the characters correspond to), and as if that set was fixed by the URI scheme. That hasn't been true in practice ๐Ÿ™ƒ Any character that gets interpreted differently when it's escaped is, in effect, reserved. On top of that, the interpreting engine on an HTTP server often depends on the resource, not just the URI scheme. So the description of reserved characters has been changed to match ๐Ÿ’–

  • The plus "+", dollar "$", and comma "," characters were added to the "reserved" set, since they're treated as reserved within the query component.
  • The tilde "~" character was added to the "unreserved" set, since it's used all over the Internet even though it's a pain to type on some keyboards.
  • The syntax for URI scheme now requires that all schemes begin with an alpha character.
  • The "user:password" form from the previous BNF was changed to a "userinfo" token, and the possibility that it might be "user:password" was made scheme specific. In particular, the syntax doesn't even hint at passwords in the clear ๐Ÿ”
  • The question-mark "?" character was removed from the set of allowed characters for userinfo in the authority component, since testing showed that many applications treat it as reserved for separating the query component from the rest of the URI.
  • The semicolon ";" character was added to those reserved within the authority component, since several new schemes use it as a separator within userinfo to indicate the type of user authentication.

RFC 1738 said the path was separated from the authority portion of a URI by a slash. RFC 1808 followed suit, but with a fudge: it carried the separator around as a "prefix" so the parsing algorithm could be described. RFC 1630 never had this problem, since it considered the slash to be part of the path. While writing this spec, it turned out to be impossible to accurately describe and keep the difference between these two URI:

<foo:/bar>   and   <foo:bar>

without either treating the slash as part of the path (which matches actual practice) or creating a separate component just to hold that slash. We went with the former ๐Ÿงš

G.3. Modifications from RFC 1738

The definitions of specific URL schemes and their scheme-specific syntax and semantics were moved to separate documents ๐Ÿ“š

The URL host used to be defined as a fully-qualified domain name. But lots of URLs get used without fully-qualified domain names (in contexts where full qualification isn't needed), without any host at all (as in some file URLs), or with a host of "localhost" ๐Ÿ 

The URL port is now *digit instead of 1*digit, since systems are expected to handle the case where the ":" separator between host and port is supplied without a port ๐ŸŒธ

The recommendations for delimiting URI in context (Appendix E) were adjusted to reflect current practice โœจ

G.4. Modifications from RFC 1808 ๐ŸŽ€

okay so RFC 1808 (Section 4) said an empty URL reference, one with nothing in it except the fragment identifier, is a reference to the base URL ๐Ÿซถ that sounds fine until a user agent clicks it and decides to fetch the resource again ๐Ÿ’€ the whole point of those references is to scroll the current document to the start of that fragment, not to make a brand new request. so the correct way to read an empty reference got its own description in Section 4 โœจ

the made-up Base header field got retired ๐Ÿ™ˆ it's now pointing at the Content-Location header field from MHTML [RFC2110] instead. much more legit, no notes.

RFC 1808 sorted schemes into "has the generic URI properties" and "doesn't." lowkey confusing ๐Ÿ˜ญ the only real requirement is that the document holding the relative references has a base URI that follows the generic URI syntax. it doesn't matter which scheme that base URI uses, so the wording got updated to match ๐Ÿ’…

the BNF term <net_loc> is now <authority> ๐Ÿฆ‹ <authority> is a way better name for what it actually does. and the authority is no longer stuck to the IP server syntax. it's giving freedom ๐ŸŒˆ

testing current clients showed that most deployed systems don't use the ";" character to mark trailing parameter info, and a semicolon inside a path segment doesn't change how that segment gets resolved relatively ๐Ÿงš so parameters stopped being their own component. they can show up in any path segment now, and they're out of the relative resolution algorithm entirely. the examples in Appendix C got updated to match โœจ

one little allowance: implementations are now allowed to work around misformed relative references that start with the same scheme as the base URI, but ONLY for schemes that are known to use the <hier_part> syntax. no free passes for everyone, periodt ๐Ÿ”ฅ

okay this part is legal stuff, but it's still important, so here it is in full ๐Ÿซถ

Copyright (C) The Internet Society (1998). All Rights Reserved.

This document and translations of it may be copied and furnished to others, and derivative works that comment on or otherwise explain it or assist in its implementation may be prepared, copied, published and distributed, in whole or in part, without restriction of any kind, provided that the above copyright notice and this paragraph are included on all such copies and derivative works. However, this document itself may not be modified in any way, such as by removing the copyright notice or references to the Internet Society or other Internet organizations, except as needed for the purpose of developing Internet standards in which case the procedures for copyrights defined in the Internet Standards process must be followed, or as required to translate it into languages other than English.

The limited permissions granted above are perpetual and will not be revoked by the Internet Society or its successors or assigns.

This document and the information contained herein is provided on an "AS IS" basis and THE INTERNET SOCIETY AND THE INTERNET ENGINEERING TASK FORCE DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTY THAT THE USE OF THE INFORMATION HEREIN WILL NOT INFRINGE ANY RIGHTS OR ANY IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. ๐ŸŒธ

๐Ÿ“ฆ where this page comes from