
本文探讨在文档构建器等动态环境中,`window.location.origin`无法准确获取网站有效根路径的问题。针对readthedocs等平台,通过发起http `head`请求并追踪重定向,可以异步获取到实际的基准url,从而解决版本切换时页面重定向到正确根目录的需求。这种方法尤其适用于ci/cd工具链下部署的网站。
在Web开发中,我们通常认为网站的根路径就是其域名,可以通过 window.location.origin 来获取。例如,对于 https://example.com/path/to/page.html,其 origin 是 https://example.com。然而,在某些特定的部署场景,尤其是使用自动化文档构建器(如ReadTheDocs)或持续集成/持续部署(CI/CD)工具时,网站的“有效根路径”可能并非简单的域名,而是一个包含子路径的URL。
例如,在ReadTheDocs上,https://pydata-sphinx-theme.readthedocs.io 可能会自动重定向到 https://pydata-sphinx-theme.readthedocs.io/en/stable/。这意味着对于用户而言,https://pydata-sphinx-theme.readthedocs.io/en/stable/ 才是其文档的真正“根目录”。当我们需要实现一个版本切换功能,将用户从一个不存在的页面重定向到特定版本的文档根目录时(例如,从 https://pydata-sphinx-theme.readthedocs.io/en/stable/examples/index.html 跳转到 v0.9 版本的根目录 https://pydata-sphinx-theme.readthedocs.io/en/v0.9.0/),仅仅依赖 window.location.origin 就会导致错误。
window.location.origin 仅返回协议、主机名和端口。它无法感知到服务器端进行的HTTP重定向,也无法识别出像 /en/stable/ 这样的有效子路径作为网站的实际入口。
最初的尝试可能如下所示,它使用 window.location.origin 作为基准URL:
/**
* 检查给定URL是否为相对路径,并尝试使用window.location.origin生成绝对URL。
*
* @param {string} url 需要检查和转换的URL。
* @returns {string} 转换后的绝对URL或原始URL。
*/
function makeAbsoluteUrl(url) {
// 匹配非绝对URL的正则表达式
const pattern = /^(?!(?:[a-z]+:)?\/\/)/i;
const base_url = window.location.origin; // 这里的基准URL可能不准确
// 如果是相对URL,则拼接
if (pattern.test(url)) {
// 确保拼接时处理好斜杠
const normalizedBase = base_url.endsWith('/') ? base_url.slice(0, -1) : base_url;
const normalizedUrl = url.startsWith('/') ? url.slice(1) : url;
return `${normalizedBase}/${normalizedUrl}`;
}
return url;
}上述代码在大多数标准网站上工作良好,但对于像ReadTheDocs这样,其根URL实际上是一个重定向目标(如 https://pydata-sphinx-theme--1344.org.readthedocs.build 重定向到 https://pydata-sphinx-theme--1344.org.readthedocs.build/en/1344/)的场景,它会失败。它只会得到 https://pydata-sphinx-theme--1344.org.readthedocs.build,而我们期望的是 https://pydata-sphinx-theme--1344.org.readthedocs.build/en/1344/。
解决这个问题的关键在于,服务器在进行重定向时,会将请求导向其真正的入口路径。我们可以利用 fetch API 发送一个 HEAD 请求到 window.location.origin,并观察其最终重定向的URL。fetch API 的 Response 对象有一个 url 属性,它会返回请求经过所有重定向后的最终URL。
这种方法的优点是:
下面是利用 fetch API 实现的 makeAbsoluteUrl 函数:
/**
* 检查给定URL是否为相对路径,并根据网站的实际根路径生成绝对URL。
* 特别适用于处理通过HTTP重定向确定实际根路径的场景。
*
* @param {string} url 需要检查和转换的URL。
* @returns {Promise<string>} 返回一个Promise,解析为转换后的绝对URL。
*/
async function makeAbsoluteUrl(url) {
// 匹配非绝对URL(不以协议或双斜杠开头的URL)
const pattern = /^(?!(?:[a-z]+:)?\/\/)/i;
let effectiveBaseUrl;
try {
// 发起HEAD请求到当前页面的origin,追踪重定向以获取真实的基准URL
// res.url 将包含最终重定向后的URL
const response = await fetch(window.location.origin, { method: "HEAD" });
effectiveBaseUrl = response.url;
} catch (error) {
console.error("获取网站有效根路径失败,回退到window.location.origin:", error);
// 如果获取失败(例如网络错误或CORS限制),回退到window.location.origin作为基准
effectiveBaseUrl = window.location.origin;
}
// 如果URL是相对路径,则将其与有效基准URL拼接
if (pattern.test(url)) {
// 确保基准URL末尾没有斜杠,且相对URL开头没有斜杠,避免双斜杠
const normalizedBase = effectiveBaseUrl.endsWith('/') ? effectiveBaseUrl.slice(0, -1) : effectiveBaseUrl;
const normalizedUrl = url.startsWith('/') ? url.slice(1) : url;
return `${normalizedBase}/${normalizedUrl}`;
}
// 如果URL已经是绝对路径,则直接返回
return url;
}
// 示例用法 (在实际应用中,您可能需要在一个异步函数中调用它)
async function exampleUsage() {
const relativePath = "some/page.html";
const absolutePath = await makeAbsoluteUrl(relativePath);
console.log(`转换后的绝对路径: ${absolutePath}`);
const existingAbsolutePath = "https://example.com/another/page.html";
const result = await makeAbsoluteUrl(existingAbsolutePath);
console.log(`已是绝对路径: ${result}`);
}
// 调用示例
exampleUsage();通过上述方法,我们能够更健壮地识别出网站的实际有效根路径,从而在复杂的部署环境中实现精确的URL构建和重定向逻辑,提升用户体验和应用稳定性。
以上就是在非域根路径场景下,如何精确获取网站的有效根路径的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号