Root-relative links in HTML sites that work both locally and on the web

Viewed 417

Root-relative links are usually accomplished by prefacing a href attribute with /, like so:

<a href="/path_to_file">

The problem is that this doesn't work with locally run sites, as the / will link to actual root of the computer's filesystem rather than the website's base URL.

Is there a way to make root-relative links that function properly not only in traditional web-hosted cases but also when run locally?

1 Answers

You can provide a base URI in the head:

<base href="https://example.com/" />

With this base element, <a href="/path_to_file"> will link to https://example.com/path_to_file, no matter the current document host.

Related