英文:
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;
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论