主题
assetPrefix
注意:部署到 Vercel 会自动为你的 Next.js 项目配置全局 CDN。你无需手动设置资源前缀。
¥Attention: Deploying to Vercel automatically configures a global CDN for your Next.js project. You do not need to manually setup an Asset Prefix.
需要了解:Next.js 9.5+ 添加了对可自定义 基本路径 的支持,它更适合在
/docs这样的子路径上托管应用。我们不建议你为此用例使用自定义资源前缀。¥Good to know: Next.js 9.5+ added support for a customizable Base Path, which is better suited for hosting your application on a sub-path like
/docs. We do not suggest you use a custom Asset Prefix for this use case.
设置 CDN
¥Set up a CDN
要设置 CDN,你可以设置资源前缀并配置 CDN 的来源以解析为托管 Next.js 的域。
¥To set up a CDN, you can set up an asset prefix and configure your CDN's origin to resolve to the domain that Next.js is hosted on.
打开 next.config.mjs 并根据 phase 添加 assetPrefix 配置:
¥Open next.config.mjs and add the assetPrefix config based on the phase:
Next.js 将自动使用你从 /_next/ 路径(.next/static/ 文件夹)加载的 JavaScript 和 CSS 文件的资源前缀。例如,使用上述配置,对 JS 块的请求如下:
¥Next.js will automatically use your asset prefix for the JavaScript and CSS files it loads from the /_next/ path (.next/static/ folder). For example, with the above configuration, the following request for a JS chunk:
/_next/static/chunks/4b9b41aaa062cbbfeff4add70f256968c51ece5d.4d708494b3aed70c04f0.js将改为:
¥Would instead become:
https://cdn.mydomain.com/_next/static/chunks/4b9b41aaa062cbbfeff4add70f256968c51ece5d.4d708494b3aed70c04f0.js将文件上传到给定 CDN 的确切配置取决于你选择的 CDN。你需要在 CDN 上托管的唯一文件夹是 .next/static/ 的内容,应将其上传为 _next/static/,如上述 URL 请求所示。不要上传 .next/ 文件夹的其余部分,因为你不应该向公众公开你的服务器代码和其他配置。
¥The exact configuration for uploading your files to a given CDN will depend on your CDN of choice. The only folder you need to host on your CDN is the contents of .next/static/, which should be uploaded as _next/static/ as the above URL request indicates. Do not upload the rest of your .next/ folder, as you should not expose your server code and other configuration to the public.
虽然 assetPrefix 覆盖了对 _next/static 的请求,但它不影响以下路径:
¥While assetPrefix covers requests to _next/static, it does not influence the following paths:
public 文件夹中的文件;如果你想通过 CDN 提供这些资源,你必须自己引入前缀
¥Files in the public folder; if you want to serve those assets over a CDN, you'll have to introduce the prefix yourself
/_next/data/请求getServerSideProps页面。由于这些请求并非静态的,因此它们将始终针对主域发出。¥
/_next/data/requests forgetServerSidePropspages. These requests will always be made against the main domain since they're not static./_next/data/请求getStaticProps页面。为了支持 增量静态生成,即使你不使用 增量静态生成(为了保持一致性),这些请求也将始终针对主域发出。¥
/_next/data/requests forgetStaticPropspages. These requests will always be made against the main domain to support Incremental Static Generation, even if you're not using it (for consistency).