【问题标题】:Relative link not working with nginx reverse proxy相对链接不适用于 nginx 反向代理
【发布时间】: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的内容。

这一切都按预期工作,并且完美。

但是,我在页面上也有一些硬编码的&lt;a&gt; 标签:

<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


【解决方案1】:

像这样的图像:

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;
        }
    }
}

【讨论】:

  • rewrite 条件不会导致 302 吗?
  • 我在重写时编辑了我的答案,试一试,让我知道结果。
猜你喜欢
  • 2020-11-22
  • 2020-07-08
  • 2019-07-30
  • 2021-07-26
  • 2017-09-27
  • 1970-01-01
  • 2021-12-26
  • 2020-01-05
  • 1970-01-01
相关资源
最近更新 更多