Home > Software engineering >  relative src and href paths work live but not local
relative src and href paths work live but not local

Time:10-30

I was making a new path for pages on my site and was trying to figure out how to path to my stylesheet and images cleanly. Here's an element that shows my problem:


<link rel="stylesheet" href="/src/styles.css">

My local copy of my site is hosted here at "E:/Documents/WEBSITE", the local page I'm trying to link the stylesheet from is "file:///E:/Documents/WEBSITE/things/weapons.html", and the stylesheet is at "E:/Documents/WEBSITE/src/styles.css". I have the local site open on Firefox and I am using VSC to code. When I follow the href path in VSC, it brings me to the correct stylesheet. When I upload a version of the site that has the same path, it works correctly. I have the local site open on Firefox and I am using VSC to code. When I follow the href path in VSC, it brings me to the correct stylesheet.

I've looked over the code and made sure it would(and does) work otherwise. Like I said, it works when on the live site. I've placed dummy "src" folders with "styles.css" in them on my base E drive, my Documents folder, and even in the "things" folder itself. If the href were pulling from any one of these, there would be an obvious change to the local site, but none of them are pulled from with that path. When I upload a version of the site that has the same path, it works correctly. The same happens with some elements that I tried this with the src on. It simply will not work locally. The only other thing I can possibly think of is that it has a problem with the "file://" at the beginning, but I can't imagine how I would troubleshoot or avoid that. I get no errors logged. I really can't include a reproducible example of code, but what I've done that works locally and on a live site:

<link rel="stylesheet" href="../src/styles.css">

and to reiterate, this doesn't work locally, but it works on a live site:

<link rel="stylesheet" href="/src/styles.css">

And just to clarify at the end here, the path is working when the site is live, but not locally. Not the other way around.

CodePudding user response:

href="/src/styles.css" is an absolute path, not a relative one.

From file:///E:/Documents/WEBSITE/things/weapons.html it maps to something like file:///E:/src/styles.css (I think Windows file paths preserve the drive, but I'm not certain).

The browser has no way of knowing that you want file:///E:/Documents/WEBSITE/ to be the root directory of the site. The root is determined by stripping all the path information off the URL, not just parts of the path.

Absolute paths are, generally, not suitable for links used on a local file system.

Use an HTTP server. There are many free ones you can use for testing. VS Code has an extension called Live Server that makes it easy to run one.

  • Related