Skip to content
AgileLogics
5 min read

URLs and File Paths

Prerequisites: Links

Links, images, stylesheets, and scripts all point to files with a URL. Getting paths right is one of the most common beginner struggles.

Anatomy of a URL

https://www.example.com:443/blog/post.html?page=2#comments
└─┬─┘   └──────┬──────┘└┬┘└──────┬──────┘└──┬──┘└───┬───┘
scheme       host     port     path       query  fragment

Absolute and relative URLs

Take a site with this layout:

my-site/
  index.html
  about.html
  blog/
    index.html
    first-post.html
  images/
    logo.png
Written in href Points to
anywhere https://example.com/about.html absolute URL — full address
index.html about.html my-site/about.html (same folder)
index.html blog/first-post.html into the blog folder
blog/first-post.html index.html my-site/blog/index.html
blog/first-post.html ../about.html up one folder, then about.html
blog/first-post.html ../images/logo.png up one, into images
anywhere on a server /images/logo.png from the site root
  • A relative path is resolved from the folder of the current page.
  • .. means "the parent folder"; ./ means "this folder" (optional).
  • A path starting with / is root-relative: it starts from the top of the website. On a real server that's reliable from any page — but when you open files directly (file:///), / means the root of your disk, so root-relative links break. Use a local server (see Setting Up Your Environment).

The base of relative URLs

Relative URLs are resolved against the page's own address. You can see this with the URL API in a script:

<script>
  const page = "https://example.com/blog/first-post.html";
  console.log(new URL("../about.html", page).href);
  console.log(new URL("/images/logo.png", page).href);
  console.log(new URL("second-post.html", page).href);
  console.log(new URL("#comments", page).href);
</script>
https://example.com/about.html
https://example.com/images/logo.png
https://example.com/blog/second-post.html
https://example.com/blog/first-post.html#comments

Rules that save hours

  • Use lowercase file names with hyphens: first-post.html, not First Post.HTML. Many servers are case-sensitive — Logo.png and logo.png are different files there, even if they aren't on your Windows or macOS computer.
  • Avoid spaces in file names (they become %20 in URLs).
  • Use forward slashes /, never Windows backslashes \.

Practice

From blog/first-post.html, write the href for a link back to the home page my-site/index.html and the src path for images/logo.png, using relative paths.

Show solution
<a href="../index.html">Home</a>
<img src="../images/logo.png" alt="My Site">

Related developer tools