nginx - 相对链接不适用于 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/
,当然 404s 因为它被代理到http://localhost:3000/us/us/about-us/
,它不存在。
如果我window.location = '/about-us'
在浏览器控制台中执行此操作,也会发生此行为,但是输出window.location.href
is "http://localhost:8080/"
。
看起来 req tohttp://localhost:8080/about-us
最终得到了 308 to 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;
}
}
}
推荐阅读
- django - 如何在 Django 中制作可重用的页面片段?
- optaplanner - 在 OptaPlanner 的约束中使用 HardMediumSoftScore 时出现异常
- javascript - 如何在html标签中显示链接
- install4j - install4j v9.0后如何检测windows代理设置
- react-native - React Native-Styling Tab Navigator
- python - 如何在 Django ORM 中触发 bulk_create 之后的动作?
- node.js - 如何在 npm 中运行单个测试?
- reactjs - localStorage 需要时间在反应中存储令牌
- dataweave - 从 Dataweave 中的列中获取最大值
- postgresql - Postgres - 将列表拆分为行