Sub topic 2
Anatomy of a URL
A URL (Uniform Resource Locator) is the address a browser uses to find a resource and decide how to ask for it. This chapter assumes you have used a browser, have seen HTML, and can run commands in a terminal. It covers the parts of a URL, the defaults that hide some of them, and the errors people make when they build or parse URLs by hand.
The parts of a URL
Take this URL:
https://alice:[email protected]:8443/docs/guide.html?lang=en&page=2#installIt breaks down like this:
| Part | Value | Purpose |
|---|---|---|
| Scheme | `https` | Which protocol to use |
| Userinfo | `alice:secret` | Optional credentials (deprecated) |
| Host | `www.example.com` | Which machine to contact |
| Port | `8443` | Which service on that machine |
| Path | `/docs/guide.html` | Which resource on the server |
| Query | `lang=en&page=2` | Extra parameters for the resource |
| Fragment | `install` | A location inside the resource |
The full structure is scheme://userinfo@host:port/path?query#fragment. Only the scheme and the host (or a path, for some schemes) are required. Everything else is optional.
The diagram shows an important point. The parts of a URL go to different places. The fragment never leaves the browser.
Scheme
The scheme comes before ://. It names the protocol or the way to handle the resource. Common schemes are http, https, ftp, file, mailto, and data. This tutorial focuses on http and https.
The scheme also sets the default port. HTTP uses 80 and HTTPS uses 443. Schemes are not case-sensitive, and browsers normalize them to lowercase.
Not every scheme uses //. mailto:[email protected] has no host and no slashes. A data: URL carries its content inside the URL itself.
Host
The host says which server to contact. It is either a domain name such as www.example.com or an IP address such as 93.184.216.34. IPv6 addresses go in square brackets: http://[2001:db8::1]:8080/. The brackets are needed because the address contains colons, which would otherwise be confused with the port separator.
Hostnames are case-insensitive. Example.COM and example.com name the same server. A domain name is read from right to left, from the most general part to the most specific:
comis the top-level domain.exampleis the domain registered under it.wwwis a subdomain chosen by the owner.
When the host is a name, the browser must turn it into an IP address before it can connect. The next chapter covers that step. For now, note that the host is the part of the URL used for DNS.
Port
The port is a number from 0 to 65535 that selects a service on the machine. A single server can run many services, and the port tells the operating system which one should receive the connection.
If the URL leaves out the port, the browser uses the scheme's default. These two URLs are equivalent:
https://example.com/
https://example.com:443/Browsers drop a port that matches the default, so you rarely see :443 in the address bar. You do see non-default ports during development, such as http://localhost:3000/. Port 3000 is a convention, not a rule. The server picks it.
Path
The path names the resource on the server. It begins with / and uses / to separate segments. It looks like a file system path, but that is only a convention. The server decides what a path means. /docs/guide.html might map to a file, or a program might generate the response from a database.
Two things catch people out:
- Paths are usually case-sensitive.
/Aboutand/aboutcan be different resources. - A trailing slash can matter.
/docsand/docs/are different paths, and servers often redirect one to the other.
Relative paths are resolved against the current page. If you are on https://example.com/docs/guide.html, then a link to images/a.png goes to /docs/images/a.png. A link to /images/a.png goes to /images/a.png on the same host. A link to ../a.png goes up one level, to /a.png.
Query string
The query starts after ? and holds parameters as name=value pairs joined by &. The server reads them as extra input for the resource.
/search?q=http+caching&page=2The query is part of the request sent to the server, and it is part of what caches use to tell two URLs apart. /search?page=1 and /search?page=2 are different cache entries.
Because URLs appear in browser history, server logs, and the Referer header, do not put secrets such as passwords or tokens in the query string.
Fragment
The fragment starts after #. It points to a place inside the resource, such as a heading with a matching id attribute. The browser scrolls to that element after the page loads.
The browser does not send the fragment to the server. A request for https://example.com/guide.html#install asks for /guide.html, and the browser handles #install locally. That means server code cannot read the fragment. Single-page applications use this behavior to keep state in the URL without triggering a new request.
Percent-encoding
URLs can only contain a limited set of ASCII characters. Other characters, and characters that have special meaning in a URL, are written as a percent sign followed by two hexadecimal digits of the byte value. A space becomes %20. In query strings, forms often write a space as + instead.
| Character | Encoded | Why |
|---|---|---|
| space | `%20` | Not allowed in a URL |
| `&` | `%26` | Separates query parameters |
| `=` | `%3D` | Separates a name from its value |
| `#` | `%23` | Starts the fragment |
| `é` | `%C3%A9` | Non-ASCII, encoded as UTF-8 bytes |
The common mistake is building a URL by joining strings. If a user types Tom & Jerry into a search box and you paste it into the query, the & ends the parameter early and the rest is read as a new one. Use a URL library instead.
const url = new URL("https://example.com/search");
url.searchParams.set("q", "Tom & Jerry");
url.hash = "results";
console.log(url.href);
console.log(url.hostname);
console.log(url.port === "" ? "default port" : url.port);
console.log(url.pathname);
console.log(url.searchParams.get("q"));This prints:
https://example.com/search?q=Tom+%26+Jerry#results
example.com
default port
/search
Tom & JerryThe URL class is built into browsers and Node.js. It encodes the value on the way in and decodes it on the way out. Note that url.port is an empty string when the port is the default for the scheme.
Internationalized domain names are handled separately. A name such as münchen.de is converted to an ASCII form called Punycode (xn--mnchen-3ya.de) before DNS sees it. Only the path and query use percent-encoding.
Absolute and relative references
A full URL with a scheme is absolute. Links in HTML are often relative references, and the browser resolves them against a base URL. Two forms are worth knowing:
- A scheme-relative or protocol-relative reference such as
//cdn.example.com/lib.jskeeps the current scheme. It is now discouraged because everything should use HTTPS. - A fragment-only reference such as
#installstays on the same document and does not trigger a new request.
The URL constructor accepts a base as a second argument:
const base = "https://example.com/docs/guide.html";
console.log(new URL("images/a.png", base).href);
console.log(new URL("/images/a.png", base).href);
console.log(new URL("../a.png", base).href);This prints https://example.com/docs/images/a.png, https://example.com/images/a.png, and https://example.com/a.png.
Userinfo and why to avoid it
The user:password@ section is a legacy feature. Browsers have restricted it because credentials in a URL end up in history and logs. It also enables spoofing: in https://[email protected]/, the real host is evil.test, and example.com is only the username. Always read the host from the part after the last @.
Common errors
- Building URLs by string concatenation. Unescaped
&,#, or spaces change the meaning. UseURLandURLSearchParams. - Expecting the server to see the fragment. It never does.
- Ignoring case. Hostnames are case-insensitive, but paths are usually case-sensitive.
- Forgetting the default port.
http://example.comuses port 80, not 3000 or 8080. - Putting secrets in the query string. They leak through logs, history, and
Referer. - Confusing the host with the whole URL. The host is only the name between
//and the port or path.
Check your understanding
Exercise
A page at https://shop.example.com/products/list.html contains a link with href="../cart?item=7&qty=2#summary". What absolute URL does the browser resolve it to, and which parts of it does the server receive in the request?
Show answer
The absolute URL is https://shop.example.com/cart?item=7&qty=2#summary. The base path is /products/list.html, so ".." moves up from /products/ to the root, giving /cart. The server receives the path /cart and the query item=7&qty=2. The fragment "summary" is handled only by the browser. The port is the HTTPS default, 443.
Exercise
A developer writes const u = "https://example.com/search?q=" + input; where input is "C# & C++". What goes wrong, and how should it be fixed?
Show answer
The # starts a fragment, so everything after it is never sent to the server, and the & would also split the query if it came first. The server would see q=C or similar, not the full text. Fix it with URL and URLSearchParams: url.searchParams.set("q", input) encodes the value as C%23+%26+C%2B%2B, so the server receives the full string.