我正在将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/"
。
看起来req到http://localhost:8080/about-us
最终得到308到http://localhost:8080/about-us
,但我不知道为什么。更令人困惑的是,行为似乎因我使用的浏览器而异。
我做错了什么?我需要重写req路径吗?
像这样成像:
1/如果我的链接是:http://localhost:8080/us/about-us
2/它将到达您的代理并满足第一个条件:
location / {
proxy_pass http://nextjs_upstream/us/;
}
3/之后,你的服务器会将us
路径添加到你的链接中,这就是为什么它会导致:http://localhost:3000/us/us/about-us/
我的建议是在您的反向代理配置文件中添加if clause
以删除/us
if ($request_uri ~ ^(.*)/us/) {
rewrite (.*)/us/(.*)$ $1/$2;
}
您的配置文件如下所示:
events {}
http {
upstream nextjs_upstream {
server localhost:3000;
}
server {
listen 8080 default_server;
server_name _;
server_tokens off;
if ($request_uri ~ ^(.*)/us/){
rewrite (.*)/us/(.*)$ $1/$2;
}
location / {
proxy_pass http://nextjs_upstream/us/;
}
location /_next/static {
proxy_pass http://nextjs_upstream/_next/static;
}
}
}