我从未见过<base> HTML标签实际上在任何地方使用。它的使用是否存在意味着我应该避免使用的陷阱?
事实上,我从未注意到它在现代生产站点(或任何站点)上使用过,这让我对它持怀疑态度,尽管它似乎在简化我站点上的链接方面有有用的应用程序。
Edit
After using the base tag for a few weeks, I did end up finding some major gotchas with using the base tag that make it much less desirable than it first appeared. Essentially, the changes to href='#topic' and href='' under the base tag are very incompatible with their default behavior, and this change from the default behavior could easily make third party libraries outside of your control very unreliable in unexpected ways, since they will logically depend on the default behavior. Often the changes are subtle and lead to not-immediately-obvious problems when dealing with a large codebase. I have since created an answer detailing the issues that I experienced below. So test the link results for yourself before you commit to a widespread deployment of <base>, is my new advice!
我将在为什么不应该设置<base href>标记的长长的原因列表中再添加一个参数。正如许多人在这里注意到的,设置<base href>会改变#anchor和?query URL的行为——它们附加到基本href,而不是文档自己的URL的回退基础。
您可能认为设置<base href="https://example.com/the/documents/own/url">可以解决这个问题,并且一切都将正常运行。你错了。
在现实世界的web中,?query=参数一直用于会话属性(如谷歌Analytics)和许多其他事情。这些参数中有许多是专门供脚本在客户端使用的;服务器不会关心它们,也不会对它们做任何事情。
假设您正在为example.com/landing-page提供服务,其中包含<base href="example.com/landing-page">,并且页面上有一个到#菜单的链接。然后有人通过URL example.com/landing-page?source=my-marketing-campaign到达那里。
如果没有<base href>,当他们单击#菜单时,浏览器将识别页面内导航并立即跳转到该部分。
但是,由于定义的base href example.com/landing-page缺少查询参数source=my-marketing-campaign,浏览器不能确定它是一个页面内链接。因此,单击#menu将触发一个新的HTTP请求,页面(及其所有非缓存资产)将重新加载。最好的情况是,这是对各方时间和带宽的毫无意义的浪费。在最坏的情况下,状态和数据可能会丢失。
对于静态站点来说,这是没有办法的。如果您正在使用CMS,您可能会想一下,您可以动态地将<base href>设置为请求URL,包括所有参数。虽然这可以解决刷新问题,但最终会遇到缓存问题和噩梦般的安全漏洞。
底线:<base href>会给你带来麻烦,不管你把它设置成什么。不要这样做。
如果你担心恶意脚本可能会注入自己的<base href="evil.com">标记(例如在nonce重定向攻击中),2022年的最佳解决方案似乎是将base-uri指令添加到你的内容安全策略中。