Using and interpreting relative URLs

The abbreviation URL stands for Uniform Resource Locator. It is a simple way of indicating the address of a certain resource, and because of its easy format, it doesn't need a program to get parsed.

In a document with a given URL, it is possible to give the URL of another document relative to the URL of the current document. This relative URL is usually much shorter than the full URL.

Structure of an URL

An URL looks like this:
^      ^  ^      ^              ^  ^--- local URL part
|      |  |      |              |------ port number
|      |  |      ---------------------- hostname of server, or IP address
|      |  ----------------------------- password (optional)
|      -------------------------------- username (optional)
--------------------------------------- protocol name

In most cases, the username, password and port number are omitted. It is also possible that the local URL part ends in a slash, in which case it is called a directory URL.

If the local URL starts with a slash, it is called an absolute local URL, otherwise it is called a relative (local) URL.

What are relative URLs?

Put simply, it's an URL which needs some processing before it is valid. It is a local URL, from which certain information is left out. Often this means some directory names have been left off, or the special sequence ../ is being used.

The "relative" comes from the fact that the URL is only valid relative to the URL of the current resource.

Resolving relative URLs

As said, a relative URL needs the URL of the current resource to be interpreted correctly. With some simple manipulations, the relative URL is transformed into an absolute URL, which is then fetched as usual.

A relative URL is always a local URL. The first part is therefore always the same as that of the current URL. The relative URL is then turned into an absolute local URL with the following simple steps:

  1. Omit the filename of the current absolute local URL, if it's not a directory URL.
  2. For every ../ at the beginning of the relative URL, chop off one directory name from the current directory URL.
  3. Append the local URL to the current one.

A few simple examples

In these examples, we assume that the full URL of the current document is

Relative URL: myessay.html

The full URL for this relative URL is

Relative URL: pics/background.gif

The full URL for this relative URL is

Relative URL: ../cgi-bin/

The full URL for this relative URL is

Note that it is not necessarily true that the ../ bit in a relative URL refers to going "up" one directory on the server. It may often be the case, since that's the most simple and common way to do it, but the ../ applies to the URL, not the actual directory tree on the server.

As you can see in the last example, it is quite possible that ../ ends you in a totally different directory on the server.