apache - 使用 Apache for Next.js 反向代理时加载核心脚本失败
问题描述
当我在测试机器上托管 Next.js 应用程序时,应用程序会通过 URL http://localhost:2301 在本地加载。不幸的是,如果我使用 Apache 作为反向代理并尝试通过https://test-machine.example.com/test之类的 URL 从外部访问同一个应用程序,我会在浏览器控制台中看到许多类似以下的错误:
Loading failed for the <script> with source “https://test-machine.example.com/_next/static/chunks/webpack-61095c13c5984b221292.js”. test:1:1
Loading failed for the <script> with source “https://test-machine.example.com/_next/static/u5aVcss65ePhqhGxwvtAM/_ssgManifest.js”. test:1:1
Loading failed for the <script> with source “https://test-machine.example.com/_next/static/chunks/framework-64eb7138163e04c228e4.js”. test:1:1
Loading failed for the <script> with source “https://test-machine.example.com/_next/static/chunks/main-a3a79aff3ff232b41814.js”. test:1:1
Loading failed for the <script> with source “https://test-machine.example.com/_next/static/chunks/pages/_app-a8eaeefeae66525f4ca7.js”. test:1:1
Loading failed for the <script> with source “https://test-machine.example.com/_next/static/chunks/pages/index-e982999b584b9bc5ba94.js”. test:1:1
Loading failed for the <script> with source “https://test-machine.example.com/_next/static/u5aVcss65ePhqhGxwvtAM/_buildManifest.js”. test:1:1
我可以确认这些文件在我的测试机器上,但它们位于隐藏目录“.next”中,而不是错误暗示的目录“_next”中。
如果我使用标准端口 3000 或我当前使用的新端口 2301,似乎没有任何区别。无论是通过“npm run dev”启动站点的开发实例还是通过“npm run build; npm run start”启动生产实例,我都会得到相同的行为
conf.d 中的我的虚拟主机文件类似于以下内容:
<VirtualHost *:80>
ServerName test-machine.example.com
RewriteEngine on
RewriteRule .* https://test-machine.example.com [R=301,QSA,L]
</VirtualHost>
<VirtualHost *:443>
ServerName test-machine.example.com
SSLEngine on
SSLCertificateFile [myCertFileLocation]
SSLCertificateKeyFile [myCertKeyLocation]
SSLCertificateChainFile [myChainFileLocation]
DocumentRoot /var/www/html/test-dir
ProxyRequests off
ProxyPass /test http://localhost:2301
ProxyPassReverse /test http://localhost:2301
</VirtualHost>
如何修复我的 Apache 反向代理以正确地将“.next/static”目录树中的文件提供给我的外部浏览器客户端?
解决方案
这是一个可行的解决方案:
创建一个如下所示的 next.config.js 文件:
module.exports = {
basePath: '/test',
}
现在修改 Apache 的 VHost conf 文件中的 localhost 代理条目,以反映对 basePath 的更改,如下所示:
<Location "/test">
ProxyPreserveHost On
ProxyPass http://localhost:2301/test
ProxyPassReverse http://localhost:2301/test
</Location>
这将确保“虚拟目录”和 next.js 用作项目根目录的目录相同,并且代理按预期工作。我喜欢使用<Location>
标签来定义代理的范围,以防我需要在其中添加任何 Rewrite 或 Redirects 或排除项。注意 Location 标签的使用改变了ProxyPass和ProxyPassReverse的语法
推荐阅读
- swiftui - 在 SwiftUI 中滚动时,许多项目列表崩溃,我该如何解决?
- angular - 我无法将参数传递给变量未定义的函数,Angular 11
- python - Python、Pandas、SQLAlchemy:比保存整个数据框更好的方法?
- azure - 将项目发布到 Azure 后出现内部服务器错误 (500)
- python - 每当我运行这个文件时,我都会得到一个 IndexError: string index out of range,不确定我在哪里出错了
- bash - 运行 bash 函数
- java - 如何将参数从 Java 控制器传递到 Thymeleaf 模板
- javascript - 使用javascript将字符串转换为字符串矩阵
- python - 获取频道删除器 discord py
- php - 仅当用户更改 laravel 中的任何内容时才更新数据