如何解决相对链接不适用于Nginx反向代理
我正在反向将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/
,它被代理到http://localhost:3000/us/us/about-us/
(当然不存在,当然是404s)。
如果我在浏览器控制台中执行window.location = '/about-us'
,也会发生此行为,但是window.location.href
的输出是"http://localhost:8080/"
。
看来http://localhost:8080/about-us
的要求最终得到了http://localhost:8080/about-us
的308,但我不确定为什么。更令人困惑的是,根据使用的浏览器,行为似乎有所不同。
我在这里做错了什么?我是否需要重写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;
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。