【发布时间】:2021-01-01 02:47:59
【问题描述】:
我正在将 NextJs 应用的基本路径反向代理到每个国家/地区的不同域:
events {}
http {
upstream nextjs_upstream {
server localhost:3000;
}
server {
listen 8080 default_server;
server_name _;
server_tokens off;
location / {
proxy_pass http://nextjs_upstream/us/;
}
location /_next/static {
proxy_pass http://nextjs_upstream/_next/static;
}
}
}
这很好,我可以转到http://localhost:8080 并查看我希望看到的内容——来自http://localhost:3000/us/ 的页面。
此外,如果我添加这样的内容:
<Link href='/about-us'>
<a>NextJs Link</a>
</Link>
然后点击它,我正确地被发送到http://localhost:8080/about-us,它显示来自http://localhost:3000/us/about-us的内容。
这一切都按预期工作,并且完美。
但是,我在页面上也有一些硬编码的<a> 标签:
<a href="/about-us">
Normal link
</a>
您可以看到这是一个典型的相对 URL 链接。但是,当我点击它时,浏览器会将我导航到 http://localhost:8080/us/about-us/,当然是 404,因为它被代理到 http://localhost:3000/us/us/about-us/,它不存在。
如果我在浏览器控制台中执行window.location = '/about-us',也会出现这种情况,但是window.location.href 的输出是"http://localhost:8080/"。
看起来http://localhost:8080/about-us 的请求最终得到了http://localhost:8080/about-us 的 308,但我不知道为什么。更令人困惑的是,行为似乎因我使用的浏览器而异。
我在这里做错了什么?我需要重写req路径还是什么?
【问题讨论】:
-
为避免重写(强烈推荐),您不应在代理传递中使用路径前缀。请参阅此问题和我的回答,了解有关为此构建架构的一般原则-希望它有所帮助-stackoverflow.com/questions/63716880/…
-
@TarunLalwani 谢谢,但我认为这根本与 NextJs 无关。如果我在源站公开一个简单的 Python 服务器,也会出现同样的 URL 问题。
-
@j_d,是的,任何呈现的 html 都是如此。这个想法是生成的 html 应该在其链接中也包含基本 url,以便您可以使用通过 build 提供的 baseurl 构建 html
标签: nginx proxy devops reverse-proxy nginx-reverse-proxy