如何解决将 Apache 用于 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 配置文件中修改您的 localhost 代理条目以反映对 basePath 的更改,如下所示:
<Location "/test">
ProxyPreserveHost On
ProxyPass http://localhost:2301/test
ProxyPassReverse http://localhost:2301/test
</Location>
这将确保“虚拟目录”和 next.js 用作项目根目录的目录相同,并且代理按预期工作。我喜欢使用 <Location>
标记来定义代理的范围,以防我需要在其中添加任何重写或重定向或排除项。请注意 Location 标签的使用改变了 ProxyPass 和 ProxyPassReverse
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。