You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Next.js与Strapi项目中打开外部URL出现localhost前缀如何解决?

问题原因

跳转路径拼接localhost前缀的核心原因是Strapi中存储的链接缺失http/https协议头,浏览器会默认将无协议的路径识别为当前站点的相对路径,自动拼接当前域名前缀,该问题和使用<a>标签还是next/link组件无关。

解决方案

方案1:规范CMS录入规则(优先推荐)

要求内容录入人员在Strapi中填写链接时,必须补全完整协议,比如填写https://www.google.com而非仅填写www.google.com,从数据源层面直接解决问题。

方案2:前端自动补全协议头

如果无法限制CMS录入规则,可以在前端增加逻辑自动为无协议的链接补全https://,代码示例如下:

// 封装链接格式化工具函数
const formatExternalUrl = (url) => {
  if (!url) return ''
  return url.startsWith('http://') || url.startsWith('https://') ? url : `https://${url}`
}

// a标签调用示例
<a href={formatExternalUrl(item.LinkedIn)} target="_blank" rel="noopener noreferrer">
  <img
    style={{
      height: "20px",
      width: "20px",
      backgroundColor: "white",
    }}
    src="linkedin.svg"
    alt="领英跳转图标"
  />
</a>

如果使用next/link组件,逻辑完全一致,仅需替换标签即可:

import Link from 'next/link'

<Link href={formatExternalUrl(item.LinkedIn)} target="_blank" rel="noopener noreferrer">
  <img
    style={{
      height: "20px",
      width: "20px",
      backgroundColor: "white",
    }}
    src="linkedin.svg"
    alt="领英跳转图标"
  />
</Link>

注:新增rel="noopener noreferrer"是新窗口打开外部链接的安全规范,可避免潜在的安全风险。

内容的提问来源于stack exchange,提问作者JJM50

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 08:06:03