Next.js 重写有效,但 JavaScript 和 CSS 为 404。

huangapple go评论74阅读模式
英文:

Next.js rewrites work, but Javascript and CSS is 404

问题

我试图在与suggested on this guide中建议的相同域名下运行多个Vercel/Next.js项目。

我所有不同的应用程序都有非常不同的要求,因此将它们分成自己的项目是有道理的。

我有一个主要的Next.js项目,将在mysite.com上运行。这个项目包含了对其他项目的重写:

const rewrites = async () => [
  {
    source: "/topic/",
    destination: "https://forums.mysite.com/topic/",
  },
  {
    source: "/topic/:match*",
    destination: "https://forums.mysite.com/topic/:match*",
  },
];

/**
 * @type {import('next').NextConfig}
 */
const nextConfig = {
  rewrites,
};

module.exports = nextConfig;

这些重写正在工作,但有点问题。如果我访问mysite.com/topic/,Next.js会尝试加载forums.mysite.com上的网站,但由于所有JavaScript脚本都会返回404,因此它永远不会显示。

它实际上是在mysite.com的域上尝试加载forums.mysite.com的脚本,显然它们在那里不存在。

有没有办法解决这个问题?看起来这是一个相当大的疏忽,但这绝对是Next.js建议的方式

你有什么办法可以解决这个问题吗?

英文:

I'm trying to run multiple Vercel/Next.js projects under the same domain as suggested on this guide.

All of my different apps have very different requirements so, it makes sense for me to separate them into their own projects.

I have a main Next.js project which will run at mysite.com. This project contains rewrites to the other projects:

const rewrites = async () => [
  {
    source: "/topic/",
    destination: "https://forums.mysite.com/topic/",
  },
  {
    source: "/topic/:match*",
    destination: "https://forums.mysite.com/topic/:match*",
  },
];

/**
 * @type {import('next').NextConfig}
 */
const nextConfig = {
  rewrites,
};

module.exports = nextConfig;

These rewrites are working, kind of. If I visit mysite.com/topic/ Next.js attempt to load the site at forums.mysite.com, however it never displays because all Javascript scripts go to 404.

It's essentially attempting to load forums.mysite.com's scripts on mysite.com's domain, where they obviously don't exist.

Is there any way around this? Seems like a pretty big oversight but this is definitely the way that Next.js suggests this is done.

Any ideas on how I can fix this?

答案1

得分: 0

问题实际上是由Next.js加载其脚本的方式引起的。它们都是相对于根目录的绝对路径(/_next/script而不是https://example.com/_next/script)。

解决方案是使用assetPrefix配置:

const nextConfig = {
  rewrites,
  assetPrefix: 'https://example.com',
};

module.exports = nextConfig;
英文:

So the issue is actually caused by the way Next.js loads its scripts. They're all absolute to the root (/_next/script instead of (https://example.com/_next/script).

So the solution is to use the assetPrefix config:

const nextConfig = {
  rewrites,
  assetPrefix: 'https://example.com',
};

module.exports = nextConfig;

huangapple
  • 本文由 发表于 2023年6月26日 04:44:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/76552332.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定