Using Root-Relative Links With Subdomain

2019-07-31 23:43发布

I have inherited a website where the previous developer has coded all links relative to the site root, with a leading backslash in each link:

<link href="/css/file.css" />
<script src="/js/file.js"></script>

This works great for when the site is hosted on a server, as the links will equate to:

http://www.example.com/css/file.css
http://www.example.com/js/file.js

However, I'm trying to get these links to work correctly when called from within a subfolder for local testing. Specifically, I'm using WAMP, and have moved the entire code to a local folder called site at http://localhost:8080/site/.

I can't use the root of localhost, as WAMP stores various files there (including an index that would get overwritten).

The obvious solution, as many posts here on StackOverflow suggest, is to simply use folder-relative links, such as:

<link href="css/file.css" />
<script src="js/file.js"></script>

However, there are literally hundreds of hard-coded root-relative links in various different files, so it would be great having to avoid altering every single one of them if possible.

To avoid having to edit every link, I've tried setting an HTML <base> tag and specifying the folder directly:

<base href="http://localhost:8080/site/">

However, this doesn't seem to work.

Is <base> incompatible with root-relative links?

Is there any way I can easily have all files reference http://localhost:8080/site/ without having to manually edit each one of their preexisting root-relative links? Or will I have to manually update each one to be folder-relative?

2条回答
看我几分像从前
2楼-- · 2019-08-01 00:26

Is <base> incompatible with root-relative links?

No, but an absolute path is still an absolute path. It will resolve relative to http://localhost:8080/site/ by dropping /site/.

If you want to use absolute paths and not keep your development sites in subdirectories, then configure your HTTP server to use Virtual Name Hosting.

Add custom hostnames (either in the DNS server for your LAN or in the hosts file on your development system), such as site.localhost, and set the DocumentRoot in a virtual host.

查看更多
我欲成王,谁敢阻挡
3楼-- · 2019-08-01 00:37

Have you tried using the replace function in your IDE? You can simply replace all the ="/ with =". It'll save you a lot of work and stress.

查看更多
登录 后发表回答