The right way of setting <a href=""> when it's a local file

sameold picture sameold · Aug 18, 2012 · Viewed 182.8k times · Source

I'm trying to link to a local file. I've set href as follows:

<a href="file://C:/path/to/file/file.html">Link Anchor</a>
  • In Firefox, when I right click and "open link in new tab", nothing happens.

  • When I right click and "copy link location", then manually open a new tab and paste the copied link, it works fine. So it seems my file:// syntax is fine. I've also tried it with 3 slashes like file:/// but it's the same result.

What am I doing wrong?

Answer

Jukka K. Korpela picture Jukka K. Korpela · Aug 19, 2012

By definition, file: URLs are system-dependent, and they have little use. A URL as in your example works when used locally, i.e. the linking page itself is in the user’s computer. But browsers generally refuse to follow file: links on a page that it has fetched with the HTTP protocol, so that the page's own URL is an http: URL. When you click on such a link, nothing happens. The purpose is presumably security: to prevent a remote page from accessing files in the visitor’s computer. (I think this feature was first implemented in Mozilla, then copied to other browsers.)

So if you work with HTML documents in your computer, the file: URLs should work, though there are system-dependent issues in their syntax (how you write path names and file names in such a URL).

If you really need to work with an HTML document on your computers and another HTML document on a web server, the way to make links work is to use the local file as primary and, if needed, use client-side scripting to fetch the document from the server,