我使用App router编写了一个nextjs14项目,并尝试通过反向代理部署在apache上。我试图找出在 next.config.mjs 中使用 basepath 和 assetPrefix 的正确方法,以便它能够正确地从构建文件中的 apache 服务器上提供所有内容。我有一个大案例“它在开发中有效,但在产品中无效”。
当我运行 npm run start 时,我的应用程序在 localhost:5003 上运行。它应该反向代理到http://10.34.11.17/staff-directory。当我运行 npm run dev 时,它在 localhost:3000 上运行。
我的反向代理设置如下
<VirtualHost *:80>
ServerName 10.34.11.17
DocumentRoot /var/www/html
<Directory /var/www/html>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>
# Proxy for /staff-directory/
ProxyPass /staff-directory/ http://localhost:5003/
ProxyPassReverse /staff-directory/ http://localhost:5003/
</VirtualHost>
我使用两个环境:.env.development 和 .env.Production 它们分别在开发和生产中激活。
#.env.development
NEXT_PUBLIC_ASSET_PATH='http://localhost:3000'
NEXT_PUBLIC_BASE_PATH=''
#.env.production
NEXT_PUBLIC_ASSET_PATH='http://10.34.11.17/staff-directory'
NEXT_PUBLIC_BASE_PATH='/staff-directory'
我的应用程序代码中的所有 router.push 都不包含任何基本路径,例如。
router.push(`/employee/${staff.id}`);
但是,我的 api 获取调用都包含我的公共资产路径,例如。
const res = await fetch(`${process.env.NEXT_PUBLIC_ASSET_PATH || 'http://localhost:3000'}/api/staff/${id}`
最后,这是我的 next.config.mjs 的相关部分
const nextConfig = {
basePath: process.env.NEXT_PUBLIC_BASE_PATH,
assetPrefix: process.env.NEXT_PUBLIC_ASSET_PATH,
trailingSlash: false,
这仅在加载 html 的 prod (npm run start) 中给我带来了问题,但找不到 _next 文件夹中的静态资源 404。在我的本地笔记本电脑上运行 npm run dev 运行良好。
编辑:我找到了我的 _next 文件夹现在的服务位置: http://10.34.11.17/staff-directory/staff-directory/_next
作为参考,如果正确完成,应该在 http://10.34.11.17/staff-directory/_next 提供服务。
我认为添加基本路径可能也会影响 assetPrefix
我明白了。
我完全从 next.config.mjs 中删除了 basePath。 相反,我像这样手动将基本路径添加到每个 router.push
router.push(`${process.env.NEXT_PUBLIC_BASE_PATH}/employee/${staff.id}`);
代理将服务器上的 http://localhost:3000 定向到我的 Intranet 上的 http://10.34.11.17/staff-directory。在 next.config.mjs 中添加基本路径实际上也为我的资源文件夹 _next 添加了前缀。它从 http://10.34.11.17/staff-directory/_next 服务到 http://10.34.11.17/staff-directory/staff-directory/_next .